首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java同步10个线程

用Java同步10个线程
EN

Stack Overflow用户
提问于 2014-11-01 22:01:06
回答 1查看 50关注 0票数 0

我为什么要

22291 3091 0 351 0 1423 0 0 0

而不是

0 0 0

当我在Java中运行这段代码时:

代码语言:javascript
复制
import java.lang.Thread;

class MainThread {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) new MyThread().start();
    }
}

class MyThread extends Thread {
    static int counter = 0;
    static Object mutex = new Object();
    public void run() {
        synchronized (mutex) {
            for (int i = 0; i < 1000000; i++) counter = counter + 1;
            for (int i = 0; i < 1000000; i++) counter = counter - 1;
        }
        System.out.print(counter + " ");
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-01 22:09:38

得到这个输出是因为print语句不是同步的。在thread完成两个for循环并从syncronized块中存在之后,counter = 0

但是在输出counter之前,其他一些线程进入syncronized块并开始递增counter

这就是前一个thread输出增量counter的原因。

代码语言:javascript
复制
public void run() {
    synchronized (mutex) {
        for (int i = 0; i < 1000000; i++) counter = counter + 1;
        for (int i = 0; i < 1000000; i++) counter = counter - 1;
    }
    // Here the current thread exited the sync block and some other thread get into this block  
    // and started incrementing the counter

    System.out.print(counter + " "); // your thread prints incremented counter
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26693707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档