请问一个java线程问题 有代码 请高手解答

2025-05-16 23:29:47
推荐回答(1个)
回答1:

public class ThreadDemo {

public static void main(String[] args) {
new NewThread();开始一个新的线程
try{
for(int i=5;i>0;i--){
System.out.println("Main Thread:"+i);输出 是第几个线程
Thread.sleep(1000);在此处睡1000毫秒
}
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");

}
System.out.println("Main thread exiting.");线程结束的标识
}

}
class NewThread implements Runnable{自定义的启动线程的类
Thread t;
NewThread(){ 被上面调用的方法
t=NewThread(this,"Demo Thread");开始一个线程 ,名字为Demo Thread
System.out.println("Child thread");
t.start();开始了
}
public void run(){是自动执行的方法,无需手动调用
try{
for(int i=5;i>0;i--){
Thread.sleep(500);
}
}catch(InterruptedException e){
System.out.println("Child interrupted.");
}
System.out.println("Exiting chaild thread.");
}
}