This can be solved using two Object monitor.
- One object monitor is to notify PrintingCapital after printing ASCII code.
- Second object monitor is to notify PrintingASCII after printing particular ASCII value.
So the two threads prints their values alternatively to achieve the required result.
I used String.class as second object monitor since the main is not allowed to be changed. You can use any other object as monitor if you can access the main method.
class PrintingASCII extends Thread {
private Object ob1;
private Object ob2;
public PrintingASCII(Object ob1) {
this.ob1 = ob1;
}
public void run() {
try {
for (int i = 65; i <= 90; i++) {
synchronized(ob1) {ob1.wait();}
System.out.println(i);
synchronized(String.class) {String.class.notify();}
}
}catch (Exception e) {
System.out.println("Exc : "+e);
}
}
}
class PrintingCapital extends Thread {
private Object ob1;
private Object ob2;
public PrintingCapital(Object ob1) {
this.ob1 = ob1;
}
public void run() {
try {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.println(i);
synchronized(ob1) {ob1.notify();}
synchronized(String.class) {String.class.wait();}
}
}catch (Exception e) {
System.out.println("Exc : "+e);
}
}
}
public class Main {
public static void main(String[] args) {
Object ob1 = new Object();
PrintingASCII thread1 = new PrintingASCII(ob1);
PrintingCapital thread2 = new PrintingCapital(ob1);
thread1.start();
thread2.start();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…