To write a printer class
Write a two-way
1 Public classPrinter {2 3 Public voidprint1 ()4 {5 6System.out.print ("Micro");7System.out.print ("Cold");8System.out.print ("the");9System.out.print ("Rain");Ten System.out.println (); One } A Public voidPrint2 () - { - theSystem.out.print ("Good"); -System.out.print ("People"); - System.out.println (); - + - } +}
Purpose: To enable two threads to execute two methods in this class
Line Cheng:
Public class extends Thread { publicstatic Printer p1; @Overridepublicvoid run () { for (int i = 1; I <=500; i++) { p1.print1 ();} }
Thread Two:
Public class Implements runnable{ publicstatic Printer p2; @Override publicvoid run () { for (int i = 1; I <=500; i++) { p2.print2 (); }}}
Method calls in the test class
Public class Test {publicstaticvoid main (string[] args) { Printer p=New Printer (); MyThread T1=new MyThread (); T1.p1=p; T1.start (); MyThread2 t2=new MyThread2 (); T2.P2=p; thread T3=new thread (T2); T3.start (); }}
The following occurs: Because the programmer cannot manually intervene the CPU to allocate thread resources
Workaround: Add a sync lock so that when one thread finishes executing, another thread has the right to execute
Public classPrinter { Public voidprint1 () {synchronized( This) {System.out.print (Micro); System.out.print (Cold); System.out.print (Of); System.out.print (Rain); System.out.println (); } } Public voidPrint2 () {synchronized( This) {System.out.print (Good); System.out.print (People); System.out.println (); } }}
Resolved!!!!!!!!!
Java Thread Processing II