Home > Back-end > [simple multithreading issues] three threads respectively to print 5 A, B, C, print order for ABC...
[simple multithreading issues] three threads respectively to print 5 A, B, C, print order for ABC...
Time:09-29
My question is as follows: Why the run () method of the statement is getCount () & lt; 13? Can be seen from the output of the program finally did not end when the count value is 15, but the count value from 13, the run () method will not be called for, Or is the operation result and wait () and notifyAll () method is used, is a great god can you explain it?
A test class: Public class Test { Public static void main (String [] args) {
//create a PrintCopy class object PrintCopy PC=new PrintCopy ();
//will PrintCopy class object as a parameter to a Print The Print Print=new Print (PC);
//3 new threads, and at the same time, named "A", "B", "C" Thread the t1=new Thread (print, "A"); Thread t2=new Thread (print, "B"); The Thread t3=new Thread (print, "C");
//start the thread T1. Start (); T2. Start (); T3. The start (); }
}
Second, printing categories: Public class PrintCopy { Private int flag=1; Private int count=0;
Public int getCount () { return count; }
Public synchronized void printA () { While (flag!=1) { Try { wait(); {} catch InterruptedException (e) e.printStackTrace(); } } System. Out. Print (Thread. CurrentThread (). The getName ()); Flag=2; count++; System. The out. Print (count); NotifyAll (); }
Public synchronized void printB () { While (flag!=2) { Try { wait(); {} catch InterruptedException (e) e.printStackTrace(); } } System. Out. Print (Thread. CurrentThread (). The getName ()); Flag=3; count++; System. The out. Print (count); NotifyAll (); }
Public synchronized void printC () { While (flag! { =3)Try { wait(); {} catch InterruptedException (e) e.printStackTrace(); } } System. Out. Print (Thread. CurrentThread (). The getName ()); Flag=1; count++; System. The out. Print (count); NotifyAll (); }
}
The class Print implements Runnable { Private PrintCopy PC; Public Print (PrintCopy PC) { This. PC=PC; } Public void the run () { //print control number While (PC) getCount () & lt; 13) { If (Thread. CurrentThread (). The getName () equals (" A ")) { PC. PrintA (); } Else if (Thread. CurrentThread (). The getName () equals (" B ")) { PC. PrintB (); } Else if (Thread. CurrentThread (). The getName () equals (" C ")) { PC. The printC (); } } } } 3, printing the results A1B2C3A4B5C6A7B8C9A10B11C12A13B14C15