Home > Back-end >  Threads in JAVA test after wait awakened, executed and then wait to start from scratch, encounter pr
Threads in JAVA test after wait awakened, executed and then wait to start from scratch, encounter pr

Time:12-02

//test wait awakened threads where to begin execution after

/* t1 start print t1begin, then wait, releases the lock Num n,
T2, print t2begin, then notifyAll, should print t2over, after the run,
T1 to get locks, shall print t1over,
But the program gets stuck, not print t2over, and t1over, shows that after the notifyAll, program is stuck, this is why, */


Public class WaitTest {
Public static void main (String [] args) {
Num n=new Num (10);
Thread t=new MyThread (n);
Thread t2=new MyThread (n);
T.s etName (" t1 ");
T2. Elegantly-named setName (" t2 ");
t.start();

//run t1 t2 before
Try {
Thread.sleep (1000);
{} catch InterruptedException (e)
e.printStackTrace();
}

t2.start();

}
}

The class MyThread extends Thread {
Num n;

Public MyThread (Num n) {
This. N=n;
}

@ Override
Public void the run () {

Synchronized (n) {
System. The out. Println (currentThread (). The getName () + "begin");
Try {
N.w ait ();
{} catch InterruptedException (e)
e.printStackTrace();
}
System. The out. Println (currentThread (). The getName () + "over");
}



}
}

The class MyThread2 extends Thread {
Num n;

Public MyThread2 (Num n) {
This. N=n;
}

@ Override
Public void the run () {

Synchronized (n) {
System. The out. Println (currentThread (). The getName () + "begin");
N.n otifyAll ();
System. The out. Println (currentThread (). The getName () + "over");
}


}
}


The class Num {
int num;

Public Num (int Num) {
This. Num=num;
}
}

CodePudding user response:

Where wait operation blocks, awakened, begins execution,

CodePudding user response:

Just replied to a similar problem, see here

CodePudding user response:

Try to write code in later Posting content type] [code=language code inside [/code]
Today to see your code, you thread 2 or MyThread object, should be the new a MyThread2 object

CodePudding user response:

reference 3rd floor big hidden in the temple of the reply:
try to write code in later Posting content type] [code=language code inside [/code]
Today to see your code, you should be the new thread 2 or MyThread object, an object MyThread2


Thank you, in fact, he just finish this I will see errors, posted immediately, but this kind of mistake really good hard to find, you this method is very practical! Thank you very much!
  • Related