多线程 修改同一个值 修改不正常 的问题。

纵骑横飞 2016-09-27 07:04:25
class MyThread implements Runnable{
static int i=0;
public void run() {
while(i<10000){
i++;
}
}
}
public class ThreadTest {
public static void test1() {
long start = System.currentTimeMillis();
int j = 0;
while (j <10000) {
j++;
}
long end = System.currentTimeMillis();
System.out.println(j);
System.out.println("所用时间为" + (end - start) + "ms");
}

public static void test2() {
long start = System.currentTimeMillis();

new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
System.out.println(MyThread.i);
long end = System.currentTimeMillis();
System.out.println("所用时间为:" + ((end - start)) + "ms");
}

public static void main(String[] args) {
test1();
test2();
}
}

代码贴这 ,问为什么这么写 Thread.i 的最终值不是10000而是随机变动 ?
...全文
307 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
util_00000 2016-09-28
  • 打赏
  • 举报
回复
对于需要并发执行的线程,join没什么意义。 直接给MyThread加锁

class MyThread implements Runnable{
    static int i=0;
    public void run() {
	synchronized (MyThread.class) {
            while(i<10000){
                i++;
            }
        }
    }
}
肃穆丶 2016-09-27
  • 打赏
  • 举报
回复
需要上锁我知道,,但是最后的4个线程join,,学习了。
bichir 2016-09-27
  • 打赏
  • 举报
回复
有两个错,1.上面相加函数中必须得加锁和给i加volatile关键字, 2,显示数据时必须得等子线程运算结束后再显示结果所以得给子线程启动后调用join函数 class MyThread implements Runnable{ static volatile int i=0; static final String KEY = "threadLock"; public void run() { synchronized (KEY) { while(i<10000){ i++; } } } } public class ThreadTest{ public static void test1() { long start = System.currentTimeMillis(); int j = 0; while (j <10000) { j++; } long end = System.currentTimeMillis(); System.out.println(j); System.out.println("所用时间为" + (end - start) + "ms"); } public static void test2() { long start = System.currentTimeMillis(); Thread t1 = new Thread(new MyThread()); Thread t2 = new Thread(new MyThread()); Thread t3 = new Thread(new MyThread()); Thread t4 = new Thread(new MyThread()); t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(MyThread.i); long end = System.currentTimeMillis(); System.out.println("所用时间为:" + ((end - start)) + "ms"); } public static void main(String[] args) { test1(); test2(); } }

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧