Can wait() and notify() exist together in same synchronized method in JAVA and one thread enter the synchronized method and wait until other method enter the same synchronized method and notifyall ? i need to print thread name sequentially.using wait and notify and I am trying to use below code. Below is output response :
Waiting thread 5 Thread main exit Waiting thread 2 Waiting thread 3 Waiting thread 4 thread started 1 Waiting thread 1
public class Printthread implements Runnable{
Thread t ;
static int number = 1;
boolean check = true;
public Printthread(String name)
{
t = new Thread(this,name);
t.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
print();
System.out.println(" thread EXIT " + t.getName());
}
synchronized public void print()
{
while(Integer.parseInt(t.getName()) != number)
{
try {
System.out.println(" Waiting thread " + t.getName());
wait();
System.out.println(" resumed thread started " + t.getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(Integer.parseInt(t.getName()) == number)
{
System.out.println(" thread started " + t.getName());
number = number + 1;
notifyAll();
}
}
}
public class ThreadMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub\
Printthread p5 = new Printthread("5");
Printthread p2 = new Printthread("2");
Printthread p4 = new Printthread("4");
Printthread p3 = new Printthread("3");
Printthread p1 = new Printthread("1");
System.out.println("Thread main exit");
}
}