gpt4 book ai didi

JAVA同步块(synchronized block)在多线程环境中不起作用

转载 作者:行者123 更新时间:2023-11-30 01:45:28 26 4
gpt4 key购买 nike

我有以下代码并试图理解为什么这里没有实现同步:

class Main {
Thread t1 = new OpenServerSockets();
t1.start();
}

public class OpenServerSockets extends Thread {
@Override
public void run() {
while(true){
Thread t = new ClientResponder(clientSocket, dis, dos);
t.start();
}
}

public class ClientResponder extends Thread {
@Override
public void run(){
synchronized(this) {
// some other static method call in another class.
}
}
}

同步块(synchronized block)同时被多个线程调用。为什么会这样呢?这样使用同步块(synchronized block)不是应该确保代码的互斥执行吗?

最佳答案

我可以看到锁位于上。

Thread t1 = new ClientResponder();
Thread t2 = new ClientResponder();

现在对于 t1t2 this 指的是不同的对象。您需要一个类(class)级别的锁。

public class ClientResponder extends Thread {
@Override
public void run(){
synchronized(ClientResponder.class) {
// some other static method call in another class.
}
}
}

更好的方法是使用ReentrantLock。它提供了 syncronized 不提供的高级功能

class ClientResponder extends Thread {

public static final ReentrantLock lock = new ReentrantLock ();

@Override
public void run() {
lock.lock ();
// task.
lock.unlock ();
}
}

快速阅读引用:Java Synchronized Block for .class

租户锁:https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

关于JAVA同步块(synchronized block)在多线程环境中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com