A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 樊志伟 高级黑马   /  2013-11-23 19:38  /  2282 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

线程中join()方法好像类似了设置线程的优先级,哪个线程join()了,则主线程就必须得等这个线程执行完才能运行。那join()方法和setPriority()方法在使用的时候有什么区别呢?能不能将join()方法当作setPriority()方法一样来设置线程的优先级呢来用呢?望大神帮忙解答一下。。

评分

参与人数 1技术分 +1 收起 理由
To + 1

查看全部评分

4 个回复

倒序浏览
星期天论坛没有人吗?在线等啊
回复 使用道具 举报
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是否结束 结束了继续 否则就等着吧

评分

参与人数 1技术分 +1 收起 理由
FFF + 1 虽然没有解决问题,但是已经努力了!.

查看全部评分

回复 使用道具 举报
多谢你的回答。但,好像和我问的无关~~  
回复 使用道具 举报
其实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.     }
复制代码

评分

参与人数 1技术分 +1 收起 理由
FFF + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马