In my program Thread T1 spawns a new Thread T2 and calls join on that thread (i.e. T2.join ) and this newly spawned thread T2 calls join on T1 (i.e. T1.join). This is causing thread blocking. How this can be overcome.
My Program
public class PositiveNegativeNumberProducerV1 {
static Thread evenThread, oddThread;
public static void main(String[] args) {
oddThread = new Thread(new OddProducer(evenThread), "oddThread");
oddThread.start();
}
}
class EvenProducer implements Runnable {
Thread t;
EvenProducer(Thread t) {
this.t= t;
}
public void run() {
for(int i=1; i<=100; i++) {
if(i%2==0) {
System.out.println("i = "+i+":"+Thread.currentThread().getName());
try {
System.out.println("Now join will be called on "+t.getName()+" by thread "+Thread.currentThread().getName());
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class OddProducer implements Runnable {
Thread t;
OddProducer(Thread t) {
this.t= t;
}
public void run() {
for(int i=1; i<=100; i++) {
if(i%2!=0) {
System.out.println("i = "+i+":"+Thread.currentThread().getName());
try {
if(t==null) {
t = new Thread(new EvenProducer(PositiveNegativeNumberProducerV1.oddThread), "evenThread");
t.start();
}
if(t.isAlive()) {
System.out.println("evenThread is alive and join will be called on "+t.getName()+" by thread "+Thread.currentThread().getName());
t.join();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…