gpt4 book ai didi

java - java中使用对象锁实现同步

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

我有两个线程 thread1(打印数字)和 thread2(打印字母)。我的目标是通过同步获得以下输出:

1 a 2 b 3 c 4 d 5 e

class thread1 implements Runnable {
public void run() {

try {

for (int i = 1; i <= 5; i++) {
System.out.println("Is Thread1 holding lock of Testing.class?:"+Thread.holdsLock(Testing.class));
synchronized (Testing.class) {
System.out.println("Is Thread1 holding lock of Testing.class?:"+Thread.holdsLock(Testing.class));

try {
System.out.println(i);
Testing.class.notifyAll();
System.out.println("Thread1:Going to wait");
Testing.class.wait();
System.out.println("Thread1:Resuming from wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

System.out.println("Finsihed thread1");


} catch (Exception e) {
System.out.println(e);
}

}
}



class thread2 implements Runnable {
char[] alphabets = { 'a', 'b', 'c', 'd', 'e' };

public void run() {

try {

for (int i = 0; i < 5; i++) {
System.out.println("Is Thread2 holding lock of Testing.class?:"+Thread.holdsLock(Testing.class));
synchronized (Testing.class) {
try {
System.out.println("Is Thread2 holding lock of Testing.class?:"+Thread.holdsLock(Testing.class));
System.out.println("Thread2:Going to wait");
Testing.class.wait();
System.out.println("Thread2:Resuming from wait");
System.out.println(alphabets[i]);
Testing.class.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


} catch (Exception e) {
System.out.println(e);
}

}

}


public class Testing {

public static void main(String[] args) {
Testing w= new Testing();
thread1 t1 = new thread1();
thread2 t2 = new thread2();
Thread th1 = new Thread(t1, "");

Thread th2 = new Thread(t2, "");
try {
th1.start();
th2.start();
} catch (Exception e) {
System.out.println(e);
}

}
}

我正在获取输出:

Is Thread1 holding lock of Testing.class?:false

Is Thread1 holding lock of Testing.class?:true

1

Thread1:Going to wait

Is Thread2 holding lock of Testing.class?:false

Is Thread2 holding lock of Testing.class?:true

Thread2:Going to wait

当 Testing.class 已经被 thread1 锁定时,thread2 是如何获得锁的?另外,还有其他优雅的方式来实现这种同步吗?提前致谢。

最佳答案

阅读更多关于 Java Concurrency 的信息.

调用 wait 释放锁。

关于java - java中使用对象锁实现同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583771/

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