小编Leo*_*ott的帖子

为什么我的同步方法不能正常工作?

我有一个打印计数器的同步方法,我有 4 个线程,所以我期望计数器的最终值为 400000,因为我的计数器是一个静态变量。

但每次我运行代码时,它都会给我不同的计数器值。

以下是我的代码:

class MyThread implements Runnable{

    private static int counter=1;
    @Override
    public void run() {
        try {
            this.syncMethod();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void syncMethod() throws InterruptedException{
        for(int i=0;i<100000;i++){
            System.out.println(Thread.currentThread().getName()+" : "+counter++);
        }
    }
}

public class MyController {
    public static void main(String[] args) throws InterruptedException {
        Runnable r1=new MyThread();
        Runnable r2=new MyThread();
        Runnable r3=new MyThread();
        Runnable r4=new MyThread();
        Thread t1;
        Thread t2;
        Thread t3;
        Thread t4;
        t1=new Thread(r1,"Thread 1");
        t2=new …
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronized synchronized-block

0
推荐指数
1
解决办法
1132
查看次数