I am trying to implement a case of shared variable like semaphores. In that I have 3 thread which should be run sequentially. below is my program. Could u tell me where I am wrong?
class Test2{
private volatile static int sharedvarNEXT = 1;
public synchronized static int getSharedvarNEXT(){
return sharedvarNEXT;
}
public synchronized static void setSharedvarNEXT(int val){
sharedvarNEXT = val;
}
public static void main(String[] s){
new classACaps().start();
new classAsmall().start();
new class1().start();
}
}
class classACaps extends Thread{
public void run(){
try{
for(char c='A';c<='Z';c++){
if(Test2.getSharedvarNEXT() == 1){
System.out.println(c);
Test2.setSharedvarNEXT(2);
notify();
} else {
wait();
}
}
} catch(Exception e){
System.out.println("caught in A");
}
}
}
class classAsmall extends Thread{
public void run(){
try{
for(char c='a';c<='z';c++){
if(Test2.getSharedvarNEXT() == 2){
System.out.println(c);
Test2.setSharedvarNEXT(3);
notify();
} else {
wait();
}
}
} catch(Exception e){
System.out.println("caught in a");
}
}
}
class class1 extends Thread{
public void run(){
try{
for(int c=1;c<=26;c++){
if(Test2.getSharedvarNEXT() == 3){
System.out.println(c);
Test2.setSharedvarNEXT(1);
notify();
}else {
wait();
}
}
} catch(Exception e){
System.out.println("caught in 1");
}
}
}
expected outcome is like : A, a, 1, B, b, 2......
In that I have 3 thread which should be run sequentially.
Well you're not running sequentially - you're running the three concurrently, which is the nature of what happens when you start three separate threads.
Those threads aren't synchronizing against each other at all. It doesn't really sound like you should have three threads at all, given your requirements.
Additionally:
synchronized
blocks; both wait()
and notify()
can only be called by a thread which owns the monitor on which they're calledwait()
and notify()
on instances of Thread
is strongly discouraged, as the internals of Thread
use it themselves. I suggest you create a separate object just to synchronize/wait/notify on.Exception
at all, in general.See more on this question at Stackoverflow