gpt4 book ai didi

java - 让线程相互等待。

转载 作者:行者123 更新时间:2023-11-29 05:20:04 26 4
gpt4 key购买 nike

所以我目前有这段代码

class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}

}

class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd){
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

}

public class TestThread {
public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end
try {
T1.join();
T2.join();
} catch( Exception e) {
System.out.println("Interrupted");
}

它打印出以下输出:

Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

有什么方法可以让线程 1 减一,然后线程 2 减一,直到两者都为 1,而不是让线程 1 减为 1,然后线程 2 减为 1。

最佳答案

由于您在两个线程中共享相同的 PrintDemo 类对象,您可以将其用作锁(监视器)。

示例代码:

class PrintDemo {
public void printCount() {
try {
for (int i = 5; i > 0; i--) {
synchronized (this) {
this.notify();
}
System.out.println(Thread.currentThread().getName()+" Counter --- " + i);
synchronized (this) {
this.wait();
}
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}

public void run() {
synchronized (PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");

synchronized (PD) {
PD.notify(); // notify the last waited thread.
}
}

public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}

输出:

Starting Thread - 1 
Starting Thread - 2
Thread - 1 Counter --- 5
Thread - 2 Counter --- 5
Thread - 1 Counter --- 4
Thread - 2 Counter --- 4
Thread - 1 Counter --- 3
Thread - 2 Counter --- 3
Thread - 1 Counter --- 2
Thread - 2 Counter --- 2
Thread - 1 Counter --- 1
Thread - 2 Counter --- 1
Thread Thread - 1 exiting.
Thread Thread - 2 exiting.

视觉呈现:

enter image description here

Read more...

关于java - 让线程相互等待。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151942/

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