黑马程序员技术交流社区
标题:
问个线程的问题!
[打印本页]
作者:
heheka123
时间:
2014-4-23 11:48
标题:
问个线程的问题!
先看代码!
class Demo implements Runnable
{
public synchronized void run()
{
try
{
wait();
}
catch (InterruptedException e)
{
}
for (int x = 0;x<100 ;x++ )
{
System.out.println(Thread.currentThread().getName()+"..."+x);
}
}
}
class Demo4
{
public static void main(String[] args) throws Exception
{
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.join();
t1.start();
for (int x = 0;x<100;x++ )
{
System.out.println("main..."+x);
}
System.out.println("Over!");
}
}
复制代码
在看老师视频时候,老师说join方法是用再start()前面,该线程执行完才执行其他线程,可是我让t1线程进去后wait那了, 为什么还能执行main呢
作者:
kuroro自走核炮
时间:
2014-4-23 12:15
class Demo implements Runnable
{
public synchronized void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
for (int x = 0;x<100 ;x++ )
{
System.out.println(Thread.currentThread().getName()+"..."+x);
}
}
}
class Demo4
{
public static void main(String[] args) throws Exception
{
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.start();
t1.join();
for (int x = 0;x<100;x++ )
{
System.out.println("main..."+x);
}
System.out.println("Over!");
}
}
复制代码
我试了一下,把t1.join()放到t1.start后面,就产生阻塞效果了。
查了一下API,对于join方法的描述是这样的:
join
public final void join()
throws InterruptedException等待该线程终止。
抛出:
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的中断状态 被清除。
那么既然是等待该线程中止,应该是线程启动之后再执行这个动作吧?在线程启动之前就等待过了该线程中止,那么线程启动以后不就是不等待了么?我的理解是这样,不知道对不对。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2