代码之家  ›  专栏  ›  技术社区  ›  Khyxes

Java监视器中的同步方法

  •  0
  • Khyxes  · 技术社区  · 8 年前

    我目前正在学习在Java中使用monitor,但我不知道同步方法是如何工作的。

    所以我试着写一段代码来测试它

    import java.util.Random;
    public class ex3 extends Thread {
    
    private static int nbA=0;
    private static int nbB=0;
    public static final Random rand = new Random();
    
    public void run(){
        while(true){
            System.out.println(nbA+" "+nbB);
            try{
                Thread.sleep(rand.nextInt(500));
            }catch (Exception e ){e.printStackTrace();}
            if (rand.nextBoolean()){
                try {
                    A();
                } catch (InterruptedException e) {}
            }else{
                try {
                    B();
                } catch (InterruptedException e) {}
            }
        }
    }
    
    public synchronized void A() throws InterruptedException{
        nbA++;
        Thread.sleep(rand.nextInt(500));
        nbA--;
    }
    
    public synchronized void B() throws InterruptedException{   
        nbB++;
        Thread.sleep(rand.nextInt(500));
        nbB--;
    }
    
    public static void main(String[] argv){
        new ex3().start();
        new ex3().start();
        new ex3().start();
    }
    }
    

    我误解了什么?

    对不起,英语不好。

    2 回复  |  直到 8 年前
        1
  •  0
  •   Andy Turner    8 年前

    您正在不同的对象上同步:a synchronized this ,因此 new ex3() 实例有效地工作,就像它不同步一样。

    同步实例方法与此完全等效:

    public void A() {
        synchronized (this) {
            // The body.
        }
    }
    

    要么使用同步方法 static

    public void A() throws InterruptedException{
        synchronized (ex3.class) {
            nbA++;
            Thread.sleep(rand.nextInt(500));
            nbA--;
        }
    }
    
        2
  •  0
  •   user207421    8 年前

    我理解,虽然一个线程在同步方法内,但另一个线程不能在同步方法内

    错误的它不能在同步方法内 它可以在任何其他同步方法中,也可以在不同对象上同步相同的方法,如下所示。

    对的

    推荐文章