黑马程序员技术交流社区
标题:
多线程(join方法)的一个小问题
[打印本页]
作者:
郑文博
时间:
2012-7-8 17:23
标题:
多线程(join方法)的一个小问题
本帖最后由 郑文博 于 2012-7-8 18:49 编辑
/*
join()方法:
*/
class Demo implements Runnable
{
public void run()
{
for (int x = 0;x < 70 ;x++ )
{
System.out.println(Thread.currentThread().getName()+"-----"+x);
//Thread.yield();
}
}
}
class JoinDemo
{
public static void main(String[] args) throws Exception
{
Demo d = new Demo();
Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
t1.start();
t2.start();
t1.join();
/*
对以上这句join()方法的理解是:当一个线程A执行到另一个线程B的join()方法时,A会等待,B线程执行完,A再执行。
而这个程序通过语句看 t2来到t1的join()方法了,为什么t2没有进入等待状态?
根据join()方法,唯一解释是t2线程没有执行到t1的join()方法,那这段语句是t1跟t2两个线程是并列的吗?
若是请问怎样能够让t2执行到t1呢?
*/
for (int x = 0;x < 90 ;x++ )
{
System.out.println(Thread.currentThread().getName()+"---"+x);
}
System.out.println("over");
}
}
复制代码
求解,多谢。
作者:
温少邦
时间:
2012-7-8 18:31
看一下运行结果自己应该能想到嘛
t1和t2只有那个for循环的输出语句
而t1.join()是main线程调用的
所以t1和t2并发打印输出语句
等t1打印完毕后,主线程打印输出语句
如果要让t2执行t1.join(),方法也很多
提供一种:
class Demo implements Runnable{
Thread other=null;
public Demo(Thread other){
this.other=other;
}
public Demo(){
}
public void run(){
if(other!=null)
try{
other.join();
}catch(InterruptedException e){
e.printStackTrace();
}
for(int x=0;x<70;x++){
System.out.println(Thread.currentThread().getName()+"-----"+x);
// Thread.yield();
}
}
}
public class JoinDemo{
public static void main(String[] args) throws Exception{
// Demo d = new Demo();
Thread t1=new Thread(new Demo());
Thread t2=new Thread(new Demo(t1));//t2 输出前会执行t1.join()
t1.start();
t2.start();
t2.join();
/*
然后main线程等待t2线程.
最后顺序就为t1---t2---main
*/
for(int x=0;x<90;x++){
System.out.println(Thread.currentThread().getName()+"---"+x);
}
System.out.println("over");
}
}
复制代码
作者:
金龙
时间:
2012-7-8 18:38
呃。。其实这么说吧,这是cpu的执行权决定的,还没读到ti.join(), t1 和t2都执行完了,建议这样改进
t1.start();
t1.join();
t2.start();
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2