黑马程序员技术交流社区
标题:
关于线程中join()方法的问题
[打印本页]
作者:
樊志伟
时间:
2013-11-23 19:38
标题:
关于线程中join()方法的问题
线程中join()方法好像类似了设置线程的优先级,哪个线程join()了,则主线程就必须得等这个线程执行完才能运行。那join()方法和setPriority()方法在使用的时候有什么区别呢?能不能将join()方法当作setPriority()方法一样来设置线程的优先级呢来用呢?望大神帮忙解答一下。。
作者:
樊志伟
时间:
2013-11-23 19:52
星期天论坛没有人吗?在线等啊
作者:
RuntimeError!
时间:
2013-11-23 21:06
join(thread1);作用是让thread1执行结束再去执行下面的语句,相当于开关的作用。
而setPriority()只是把优先级提高,就像join是台灯开关,而setPriority()是调节亮度的旋钮一样
public class test1
{
public static void main(String[] args) throws InterruptedException
{
thd e1 = new thd();
thd e2 = new thd();
e1.setE(4000);
e2.setE(8000);
Thread t1 = new Thread(e1);
Thread t2 = new Thread(e2);
t1.start();
t2.start();
t1.join();
System.out.println(e1.x);
}
}
class thd implements Runnable
{
public int x = 0;
public int e = 0;
public void setE(int e)
{
this.e = e;
}
@Override
public void run()
{
for(int i = 0; i<e; i++)
{
x = i;
}
}
}
复制代码
如果是多线程 看我的代码,输出e1的时候肯定是3999,如果是输出e2就不一定了
因为线程要T1完成才能执行SOP,不管T2执行到哪,相当于一个判断把 判断T1是否结束 结束了继续 否则就等着吧
作者:
樊志伟
时间:
2013-11-23 21:24
多谢你的回答。但,好像和我问的无关~~
作者:
何丛
时间:
2013-11-23 21:30
其实Join方法实现是通过wait(Object 提供的方法)。 当main线程调用t.join时候,main线程会获得线程对象t的锁(wait 意味着拿到该对象的锁),调用该对象的wait(等待时间),直到该对象唤醒main线程,比如退出后。
源码如下:
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2