黑马程序员技术交流社区

标题: 关于线程中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()是调节亮度的旋钮一样
  1. public class test1
  2. {
  3.         public static void main(String[] args) throws InterruptedException
  4.         {
  5.                 thd e1 = new thd();
  6.                 thd e2 = new thd();
  7.                 e1.setE(4000);
  8.                 e2.setE(8000);
  9.                 Thread t1 = new Thread(e1);
  10.                 Thread t2 = new Thread(e2);
  11.                 t1.start();
  12.                 t2.start();
  13.                 t1.join();
  14.                 System.out.println(e1.x);
  15.         }
  16. }
  17. class thd implements Runnable
  18. {

  19.         public int x = 0;
  20.         public int e = 0;
  21.         public void setE(int e)
  22.         {
  23.                 this.e = e;
  24.         }
  25.         @Override
  26.         public void run()
  27.         {
  28.                 for(int i = 0; i<e; i++)
  29.                 {
  30.                         x = i;
  31.                 }               
  32.         }       
  33. }
复制代码
如果是多线程 看我的代码,输出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线程,比如退出后。
源码如下:
  1. public final synchronized void join(long millis)
  2.     throws InterruptedException {
  3.         long base = System.currentTimeMillis();
  4.         long now = 0;

  5.         if (millis < 0) {
  6.             throw new IllegalArgumentException("timeout value is negative");
  7.         }

  8.         if (millis == 0) {
  9.             while (isAlive()) {
  10.                 wait(0);
  11.             }
  12.         } else {
  13.             while (isAlive()) {
  14.                 long delay = millis - now;
  15.                 if (delay <= 0) {
  16.                     break;
  17.                 }
  18.                 wait(delay);
  19.                 now = System.currentTimeMillis() - base;
  20.             }
  21.         }
  22.     }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2