在Java中同步10个线程

在Java中同步10个线程,java,multithreading,Java,Multithreading,为什么我会受伤 2229130910035101423000 而不是 0 0 0 0 0 0 0 0 0 0 在Java中运行此代码时: import java.lang.Thread; class MainThread { public static void main(String[] args) { for (int i = 0; i < 10; i++) new MyThread().start(); } } class MyThread ext

为什么我会受伤

2229130910035101423000

而不是

0 0 0 0 0 0 0 0 0 0

在Java中运行此代码时:

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 + " ");
    }
}
导入java.lang.Thread;
类主线程{
公共静态void main(字符串[]args){
对于(int i=0;i<10;i++)new MyThread().start();
}
}
类MyThread扩展线程{
静态整数计数器=0;
静态对象互斥=新对象();
公开募捐{
已同步(互斥){
对于(int i=0;i<1000000;i++)计数器=计数器+1;
对于(inti=0;i<1000000;i++)计数器=计数器-1;
}
系统输出打印(计数器+“”);
}
}

您获得该输出是因为print语句未同步。
线程
完成两个for循环并从
同步
块存在后,
计数器=0

但是在它打印出
计数器之前,其他一些线程进入
syncronized
块并开始递增
计数器

这就是前一个
线程打印递增的
计数器的原因

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
}
public void run(){
已同步(互斥){
对于(int i=0;i<1000000;i++)计数器=计数器+1;
对于(inti=0;i<1000000;i++)计数器=计数器-1;
}
//此时,当前线程退出同步块,其他线程进入该块
//并开始增加计数器
System.out.print(计数器+“”);//线程打印递增的计数器
}

因为
打印不同步。