论坛首页 Java企业应用论坛

sleep, join的使用疑惑

浏览 3437 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2016-03-31   最后修改:2016-03-31
如下代码: 为什么最后n的值一直在变,而不是1000?
package thread;

public class JoinThread extends Thread {
    public static int n = 0;
public void run() {
for (int i=0;i<10;i++) {
try {
sleep(3);
n++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[100];
for (int i=0; i<threads.length; i++) {
threads[i] = new JoinThread();
}
for (int i=0; i<threads.length; i++) {
threads[i].start();
}
if (args.length > 0) {
for (int i=0; i<threads.length; i++) {
threads[i].join();
}
}
System.out.println("n= " + JoinThread.n);
}
}

   发表时间:2016-04-02  
第一:方法没有同步,在run方法里面加上synchronized (JoinThread.class) {},把run方法里的内容放到中括号里;
第二:main方法中的if (args.length > 0)条件判断删了;
第三:纯个人见解,main方法中的三个循环没有必要,写到一个循环里面比较好,编码习惯问题。
0 请登录后投票
   发表时间:2016-04-02  
另外,第四:静态变量n最好加上关键字volatile,被多线程操作的数据都最好加上volatile关键字,编码习惯问题。
希望能帮到你,guys。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics