java Thread Join方法学习(同步)(等待调用join的线程先执行)

38 篇文章 0 订阅
[b][size=large][color=red]join() 方法主要是让调用该方法的线程完成run方法里面的东西后,再执行join()方法后面的代码。[/color][/size][/b]


class ThreadTesterA implements Runnable {

private int counter;

@Override
public void run() {
while (counter <= 10) {
System.out.print("Counter = " + counter + " ");
counter++;
}
System.out.println();
}
}

class ThreadTesterB implements Runnable {

private int i;

@Override
public void run() {
while (i <= 10) {
System.out.print("i = " + i + " ");
i++;
}
System.out.println();
}
}

public class ThreadTester {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ThreadTesterA());
Thread t2 = new Thread(new ThreadTesterB());
t1.start();
t1.join(); // wait t1 to be finished
t2.start();
t2.join(); // in this program, this may be removed
}
}



package mythread;

public class JoinThread extends Thread
{
public static int n = 0 ;

public static synchronized void inc(){
n ++ ;
}
public void run(){
for ( int i = 0 ; i < 10 ; i ++ )
try
{
inc(); // n = n + 1 改成了 inc();
sleep( 3 ); // 为了使运行结果更随机,延迟3毫秒

}
catch (Exception e)
{
}
}

public static void main(String[] args) throws Exception{

Thread threads[] = new Thread[ 100 ];
for ( int i = 0 ; i < threads.length; i ++ )
// 建立100个线程
threads[i] = new JoinThread();
for ( int i = 0 ; i < threads.length; i ++ )
// 运行刚才建立的100个线程
threads[i].start();
for ( int i = 0 ; i < threads.length; i ++ )
// 100个线程都执行完后继续 必须加上join方法
threads[i].join();
System.out.println( " n= " + JoinThread.n);
}
}


[b][size=medium][color=blue]join方法的功能就是使异步执行的线程变成同步执行。[/color][/size][/b]也就是说,当调用线程实例的start方法后,这个方法会立即返回,[color=red]如果在调用start方法后后需要使用一个由这个线程计算得到的值,就必须使用join方法。[/color]如果不使用join方法,就不能保证当执行到start方法后面的某条语句时,这个线程一定会执行完。而使用join方法后,直到这个线程退出,程序才会往下执行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值