Skip to content
Advertisement

Can a java thread waiting with wait() ,notify itself?

I came across the following e example to implement custom suspend and wait from some website.

  // Suspending and resuming a thread the modern way.
 class NewThread implements Runnable {
     String name; // name of thread
     Thread t;
     boolean suspendFlag;
     NewThread(String threadname) {
         name = threadname;
         t = new Thread(this, name);
         System.out.println("New thread: " + t);
         suspendFlag = false;
         t.start(); // Start the thread
     }
     // This is the entry point for thread.
     public void run() {
         try {
             for (int i = 15; i > 0; i--) {
                 System.out.println(name + ": " + i);
                 Thread.sleep(200);
                 synchronized(this) {
                     while (suspendFlag) {
                         wait();
                     }
                 }
             }
         } catch (InterruptedException e) {
             System.out.println(name + " interrupted.");
         }
         System.out.println(name + " exiting.");
     }
     void mysuspend() {
         suspendFlag = true;
     }
     synchronized void myresume() {
         suspendFlag = false;
         notify();
     }
 }
 class SuspendResume {
     public static void main(String args[]) {
             NewThread ob1 = new NewThread("One");
             NewThread ob2 = new NewThread("Two");
             try {
                 Thread.sleep(1000);

                 ob1.mysuspend();

                 System.out.println("Suspending thread One");

                 Thread.sleep(1000);

                 ob1.myresume();
                 ...................

I am more concerned about the ob1.mysuspend() and ob1.myresume() calls. When my suspend is called then ob1 will be placed into the blocking queue associated with the runnable object it is using. When ob1 calls myresume, then how does it work as ob1 is already in waiting queue for the same object, can the waiting object enters another synchronised method and then signals notify to itself?How does this work?What am I missing?

Advertisement

Answer

The thread is written so that while an instance of NewThread is running, another thread can call mysuspend to suspend that running thread. Again, a thread other than the suspended thread calls myresume to resume the suspended thread.

There also appears to be a data race because mysuspend writes to suspendFlag without any synchronization. That means, the thread that needs to be suspended may not see that write immediately. mysuspend must be declared synchronized, or suspendFlag must be volatile.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement