我已经厌倦了这个问题,并最终提出了一些疑问。请帮帮我
疑问:如果任何线程处于等待状态,并且没有其他线程通知该线程,那么它永远不会结束吗?即使在使用等待(长毫秒)之后。
对于代码:我的要求来自代码(请参考我的代码):
a : 应该打印“Even Thread Finish”和“Odd Thread Finish”(顺序不是 imp ,但必须同时打印)
b: 在 main 函数中也应该打印“Exit Main Thread”
实际发生的情况:经过大量运行后,在某些情况下,它会打印“Even Thread Finish”然后挂在这里,反之亦然。在某些情况下,它会同时打印两者。
它也从不打印“退出主线程”。
那么如何修改代码,所以它必须打印所有 3 条语句。(当然最后是“Exit Main..”,因为我正在使用 join 作为 main。)
简而言之:主要开始-> t1 开始-> t2 开始,然后我需要 t2/t1 完成-> 主要完成。
请帮我解决这个问题
这是我的代码:
import javax.sql.CommonDataSource;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Share commonObj = new Share();
Thread even = new Thread(new EvenThread(commonObj));
Thread odd = new Thread(new OddThread(commonObj));
even.start();
odd.start();
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit Main Thread");
}
}
class EvenThread implements Runnable {
private Share commShare;
public EvenThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
private int number = 2;
public void run() {
System.out.println("Even Thread start");
while (number <= 50) {
if (commShare.flag == true) {
System.out.println("Even Thread" + number);
number += 2;
commShare.flag = false;
synchronized(commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
} else {
synchronized(commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Even Thread Finish");
}
}
class OddThread implements Runnable {
private int number = 1;
private Share commShare;
public OddThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
public void run() {
System.out.println("Odd Thread start");
while (number <= 50) {
if (commShare.flag == false) {
System.out.println("Odd Thread :" + number);
number += 2;
commShare.flag = true;
synchronized(commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Odd Thread Finish");
}
}
class Share {
Share sharedObj;
public boolean flag = false;
}