简体   繁体   English

为什么synchronized不能同步线程?

[英]Why synchronized can not synchronize thread?

I have set the value of the flag, but the result is not 'add' and 'sub' alternates.我已经设置了标志的值,但结果不是 'add' 和 'sub' 交替。 Why?为什么? When I look at the result, it has executed twice the 'sub' method.当我查看结果时,它执行了两次“sub”方法。 But when the 'sub' method ended, the value of the flag will be set 'false'.但是当“sub”方法结束时,标志的值将被设置为“false”。 But as a result, it printed "subxxxxx" twice continuously.但结果,它连续打印了两次“subxxxxx”。

class Resource {
    private boolean flag = true;
    private int num = 0;

// At here I have declared an add()
    public synchronized void add() throws InterruptedException {
        if (this.flag == false) {
            super.wait();
        }
        Thread.sleep(100);
        this.num++;
        System.out.println("addition:"+Thread.currentThread().getName() + this.num);
        this.flag = false;
        super.notifyAll();
    }

// At here I have declared an sub()
    public synchronized void sub() throws InterruptedException {
        if (this.flag == true) {
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
        this.flag = true;
        super.notifyAll();
    }
}

/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
        new Thread(ad, "add").start();
        new Thread(ad, "add").start();
        new Thread(sub, "sub").start();
        new Thread(sub, "sub").start();
    }
}

You seem to assume that when your wait() call finishes, that the flag has changed to what you wanted to have before you called wait() .您似乎假设当您的wait()调用完成时, flag已更改为您在调用wait()之前想要的flag There is no such guarantee, especially since you have more than two threads involved.没有这样的保证,特别是因为您涉及两个以上的线程。 You should check if you need to continue waiting.您应该检查是否需要继续等待。 Also see Wait until boolean value changes it state另请参阅等待布尔值更改其状态

But in general, these constructs are too low-level to use (unless you want to learn the nitty-gritty) and you should look at the concurreny utils package for easier higher-level constructs (like Queues, Latches, Conditions).但总的来说,这些构造太低级而无法使用(除非你想学习细节),你应该查看 concurreny utils 包以获得更简单的高级构造(如队列、锁存器、条件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 同步线程一个简单的产生reduce问题我看不懂。 为什么同步块内的 Thread.sleep 使它工作不同? - synchronized thread a simple produce reduce problem I can not understand. why Thread.sleep inside synchronized block makes it work different? 在Java中,同步块可以在任何对象引用上进行同步吗? - In Java, synchronized block can synchronize on any object reference? java同步同步失败 - java synchronized fails to synchronize 同步线程方法同时执行 - 为什么? - Synchronized thread method is executing concurrently - why? 在Java中,可以在synchronized块中进行线程切换吗? - In Java, can thread switching happen in the synchronized block? 为什么子线程中的同步方法持有主线程的锁 - why synchronized method in the sub thread hold the lock of main thread 为什么我们需要在其方法已经同步时同步StringBuffer - why do we require to synchronize StringBuffer when its methods are already synchronized 为什么同步关键字不与原始变量一起使用。 仅与方法和同步块一起使用 - Why synchronize keyword not use with primitive variable. Use only with method and synchronized block 为什么此线程允许另一个线程访问其同步方法? - Why is this thread allowing another one to access its synchronized method? 为什么同步方法允许多个线程同时运行? - why Synchronized method allowing multiple thread to run concurrently?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM