gpt4 book ai didi

java - 无法理解以下java代码中线程同步的行为

转载 作者:行者123 更新时间:2023-11-30 07:41:06 25 4
gpt4 key购买 nike

当我执行以下代码时

public class ThreadTalk {
public static void main(String[] args) {
SimpleThread obj = new SimpleThread();
Thread t = new Thread(obj, "NewThread");
t.start();
synchronized (obj) {
System.out.println("In Synchronized BLOCK");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Out of Synchronized BLOCK");
}
}
}

class SimpleThread implements Runnable {
public void run() {
System.out.println("The thread running now " + Thread.currentThread());
for (int i = 0; i < 10; i++) {
System.out.println("The val of i= " + i);
}
}
}

我得到的输出是

In Synchronized BLOCK
The thread running now Thread[NewThread,5,main]
The val of i= 0
The val of i= 1
The val of i= 2
The val of i= 3
The val of i= 4
The val of i= 5
The val of i= 6
The val of i= 7
The val of i= 8
The val of i= 9
Out of Synchronized BLOCK

我期待这样的输出

In Synchronized BLOCK
Out of Synchronized BLOCK
The thread running now Thread[NewThread,5,main]
The val of i= 0
The val of i= 1
The val of i= 2
The val of i= 3
The val of i= 4
The val of i= 5
The val of i= 6
The val of i= 7
The val of i= 8
The val of i= 9

如果我使用主线程的 Synchronized block 在 SimpleThread 对象上放置锁,当主线程即将 hibernate 时,我的 NewThread 如何运行。我的意思是 NewThread 不应该等到主线程删除锁为止在 SimpleThread 对象上,因为两个线程都在同一个对象上运行。

最佳答案

run() 和/或 start() 不获取任何锁。他们只是运行代码。实际上,您需要让 SimpleTread 与主线程采用相同的锁,以便这两个线程以某种方式同步。

我认为最好的做法是显式声明一个单独的对象用作锁,而不是尝试在 Runnable 对象上进行同步。

class ThreadTalk{
public static void main(String[] args){
Object lock = new Object();
SimpleThread obj=new SimpleThread( lock );
Thread t=new Thread(obj,"NewThread");
t.start();

synchronized(lock){
System.out.println("In Synchronized BLOCK");
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Out of Synchronized BLOCK");
}
}
}
class SimpleThread implements Runnable{
private final Object lock;
public SimpleThread( Object lock ) { this.lock = lock;}
public void run(){
synchronized( lock ) {
System.out.println("The thread running now "+Thread.currentThread());
for(int i=0;i<10;i++){
System.out.println("The val of i= "+i);
}
}
}
}

关于java - 无法理解以下java代码中线程同步的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689841/

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