gpt4 book ai didi

java - run() 方法未使用 start() 执行

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

我只想使用 join() 和 isAlive 函数。我创建了 4 个线程并在构造函数中初始化它们。我使用 start 方法启动线程。它应该调用 run() 但 run 方法没有执行。难道我做错了什么。请告诉我。预先感谢您。

  class MultiThreads implements Runnable {

String name;
Thread t;

MultiThreads(String tname) {
name=tname;
t=new Thread(this.name);
System.out.println("Thread name: " + t);
t.start(); //executing run()
}

public void run(){

try{
for(int i=1;i<11;i++){
System.out.println("Thread-"+name+ ": " + i);
t.sleep(500);
}
}catch(Exception ie){
System.out.println("An error has occurred");
}
}
}

public class JoinAlive {

public static void main(String args[]) {

//Creating New Threads by calling constructor.

MultiThreads t1=new MultiThreads("One");``
MultiThreads t2=new MultiThreads("Two");
MultiThreads t3=new MultiThreads("Three");
MultiThreads t4=new MultiThreads("Four");

System.out.println();

System.out.println("Thread-One active: " + t1.t.isAlive());
System.out.println("Thread-Two active: " + t2.t.isAlive());
System.out.println("Thread-Three active: " + t3.t.isAlive());
System.out.println("Thread-Four active: " + t4.t.isAlive());

try{
System.out.println();
System.out.println(" Waiting for One");
t1.t.join();
System.out.println(" Waiting for Two");
t2.t.join();
}catch(InterruptedException ie){
System.out.println("An error occurred");
}

System.out.println();

System.out.println("Thread-One active: " + t1.t.isAlive());
System.out.println("Thread-Two active: " + t2.t.isAlive());
System.out.println("Thread-Three active: " + t3.t.isAlive());
System.out.println("Thread-Four active: " + t4.t.isAlive());
}
}

最佳答案

t=new Thread(this.name); 就是问题所在。
您为线程指定了名称,但没有提供关联的目标 Runnable 实例。

只需使用这个构造函数:

public Thread(Runnable target, String name) 

这样:

t=new Thread(this,this.name); 

关于java - run() 方法未使用 start() 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186311/

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