I tried using a static boolean to lock and unlock two synchronized threads. So I wrote the following code:
public class Main {
public static void main(String[] args){
Thread1 t1 = new Thread1(100,'#');
Thread1 t2 = new Thread1(100,'*');
t1.start();
t2.start();
}
}
public class Thread1 extends Thread {
public static boolean lock;
int myNum;
char myChar;
public Thread1(int num, char c){
myNum = num;
myChar = c;
lock = false;
}
public synchronized void run(){
System.out.println(getName() + " is runing");
while (Thread1.lock == true){
System.out.println(getName() + " is waiting");
try{wait();}
catch(InterruptedException e){}
}
Thread1.lock = true;
for(int i = 0; i<myNum; i++){
if(i%10==0)
System.out.println("");
System.out.print(myChar);
}
Thread1.lock = false;
notifyAll();
}
}
I probably am not doing it right, because only one thread prints "mychar" and the other thread just goes into wait (), rather than waking up when I do notifyAll (). I thought this could be a good way to use a static boolean for the whole class, and then change it every time and call notifyAll () to check this flag in other objects ...
Output example:
Thread-0 is runing
Thread-1 is runing
Thread-1 is waiting
source
share