爪哇 线程连接示例
目录
线程类’s
加入 ()
method can be used to stop current execution of thread until thread it 加入 s, completes its task. So basically, it waits for the thread on which 加入 method is getting called, to die.例如:Here when you call
t1.join()
, 主要 thread will wait for t1 to complete its 开始 before resuming its execution.
1 2 3 4 5 6 7 8 |
//主线程执行 线 t1= 新 线 ( 先生 , “线程1” );t1. 开始 (); //让我们等待t1死亡 尝试 { t1. 加入 (); } 抓住 (InterruptedException e) { |
连接方法的变体
联接方法有三种变体
公共最终void 加入 ()抛出InterruptedException
调用join方法的线程死亡。
公共最终无效联接(长毫秒)引发InterruptedException
在线程上调用此方法时,它将等待以下任一操作:
- 调用join方法的线程死亡。
- 指定毫秒
公共最终无效连接(long millis,int nanos)引发InterruptedException
在线程上调用此方法时,它将等待以下任一操作:
- 调用join方法的线程死亡。
- 指定毫秒+纳秒
💡 你知道吗?
如果调用join方法的线程已经终止或尚未启动,则join方法将立即返回。
爪哇 线程连接示例
让’举一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
包 组织 . Arpit . 爪哇 2blog ; 上市 类 MyRunnable 实施 可运行 { 上市 虚空 跑 () { 尝试 { 系统 . 出 . 打印 ( 线 .currentThread(). getName () + “开始” ); //线程休眠4秒 线 . 睡觉 (4000); 系统 . 出 . 打印 ( 线 .currentThread(). getName () + “ 结束” ); } 抓住 (InterruptedException e) { // TODO自动生成的catch块 e.printStackTrace(); } } } |
创造 线 ExampleMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
包 组织 . Arpit . 爪哇 2blog ; 上市 类 线 ExampleMain { 上市 静态的 虚空 主要 ( 串 args []) { 系统 . 出 . 打印 (“开始执行主线程”); MyRunnable 先生 = 新 MyRunnable(); 线 t1 = 新 线 ( 先生 , “线程1” ); 线 t2 = 新 线 ( 先生 , “线程2” ); 线 t3 = 新 线 ( 先生 , “线程3” ); t1. 开始 (); //让我们等待t1死亡 尝试 { t1. 加入 (); } 抓住 (InterruptedException e) { e.printStackTrace(); } t2. 开始 (); 尝试 { //让我们等待1秒钟或t2死亡,以先到者为准 t2. 加入 (1000); } 抓住 (InterruptedException e1) { e1.printStackTrace(); } t3. 开始 (); //在完成主线程之前先完成所有线程 尝试 { t2. 加入 (); t3. 加入 (); } 抓住 (InterruptedException e1) { e1.printStackTrace(); } 系统 . 出 . 打印 (“主线程执行结束”); } } |
当您运行上述程序时,将得到以下输出。
线程1开始
线程1结束
线程2开始
线程3开始
线程2结束
线程3结束
主线程执行结束
让s analysis 出 put now.
- 主线程执行开始。
线 1
开始 s(Thread 1 开始 ) and as we have putt1.join()
, it will wait fort1
to die(Thread 1 end).线 2
开始 s(Thread 2 开始 ) and waits for either 1 seconds or die, but as we have put 睡觉 for 4 seconds in 跑 method, it will not die in 1 second. so 主要 thread resumes and线 3
开始 s(Thread 3 开始 )- As we have put
t2.join()
andt3.join()
. These 2 threads will get completed before exiting 主要 thread, so 线 2 will end(Thread 2 end ) and then thread 3 will end(Thread 3 end). - 主线程执行结束。
爪哇 线程联接和同步化
爪哇 线程连接方法保证 发生在之前 关系。
It means if thread t1
calls t2.join()
, then all the changes done by t2 are visible to t1.
那’有关Java线程连接示例的全部内容。