gpt4 book ai didi

Java 线程 - 按顺序调用线程

转载 作者:行者123 更新时间:2023-12-02 02:03:58 24 4
gpt4 key购买 nike

我希望线程按顺序打印出它们的名称。输出应如下所示:线程0
线程1
线程2
线程 3
线程 4
线程 5
线程1
线程2
线程 3

public class NameOutput extends Thread {
static final int N = 5;
static int activeThread = 0;

public static void main(String[] args){

for (int i = 1; i <= N; i++) {
new NameOutput().start();
}
}

@Override
public void run(){
while(true){
this.printThreadName();
}

}
private synchronized void printThreadName(){
String threadName = "Thread-"+ activeThread;
//Check if thread is in the right order
if(!threadName.equals(this.getName())){
try{
wait();
}catch (InterruptedException e){
System.out.println(this.getName()+" was interrupted!");
}
}else{
System.out.println(this.getName());
activeThread = (activeThread + 1) % N;
notifyAll();
}
}
}

不知何故,输出是如果首先选择 Thread-0,则仅选择 Thread-0。第一个线程等待后程序停止。

最佳答案

问题是您创建了多个 NameOutput,并且它们使用 their own monitor lock ,这意味着它们之间不会有“通信”(信号)。

相反,您需要一个共享监视器锁:

public class NameOutput extends Thread {
static final int N = 5;
static int activeThread = 0;
static final Object lock = new Object(); // shared monitor lock

public static void main(String[] args){

for (int i = 1; i <= N; i++) {
new NameOutput().start();
}
}

@Override
public void run(){
while(true){
this.printThreadName();
}

}
private void printThreadName(){
synchronized (lock) {
String threadName = "Thread-"+ activeThread;
//Check if thread is in the right order
if(!threadName.equals(this.getName())){
try{
lock.wait();
}catch (InterruptedException e){
System.out.println(this.getName()+" was interrupted!");
}
}else{
System.out.println(this.getName());
activeThread = (activeThread + 1) % N;
lock.notifyAll();
}
}
}
}
<小时/>

另一个问题,等等 should总是在 while 循环中使用,你可以多做一点:

private void printThreadName(){
synchronized (lock) {
while (!("Thread-"+ activeThread).equals(this.getName())) {
try{
lock.wait();
}catch (InterruptedException e){
System.out.println(this.getName()+" was interrupted!");
}
}
System.out.println(this.getName());
activeThread = (activeThread + 1) % N;
lock.notifyAll();
}
}
<小时/>

输出:

Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-0
Thread-1
Thread-2
Thread-3

关于Java 线程 - 按顺序调用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113471/

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