线程和同步方法 [英] Threading and synchronized methods

查看:78
本文介绍了线程和同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class MyThread extends Thread {
    private int i;
    public static int sum=0;
    public MyThread(int k){
      i=k;
    }




    public static void main(String[] args) throws InterruptedException{

       Thread t=new MyThread(1);
       Thread s=new MyThread(2);
       Thread p=new MyThread(3);
       t.start();
       s.start();       
    }


public synchronized void doSomething(){
    for(int i=0; i<100000; i++){
        System.out.println(this.i);
    }

}

    @Override
    public void run() {
        doSomething();

    }
}

doSomething已同步.为什么输出是随机的? 我的假设是,同步方法与同步块相同,但是该块的输出是同步的,而方法不是.

the doSomething is synchronized. why is the output random? My assumption that the synchronized method would be the same as the synchronized block but the output of the block is sync and the method isn't.

推荐答案

那里的synchronized关键字可防止对同一对象上的同步方法调用进行交错.它不会阻止对不同对象的交错方法调用.由于您有三个不同的对象,因此这三个调用可以同时运行.

The synchronized keyword there prevents synchronized method calls on the same object from being interleaved. It does not prevent interleaving method calls on different objects. Since you have three different objects, the three calls can run simultaneously.

您需要在所有三个线程共享的单个对象上进行同步.

You need to synchronize on a single object which is shared by all three threads.

这篇关于线程和同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆