Class
Public Class A extends thread {<br/> private runnable B; <br/> @ override <br/> Public void run () {<br/> // todo auto-generated method stub <br/> super. run (); <br/> synchronized (this) {<br/> B. run (); <br/> for (INT I = 0; I <10; I ++) {<br/> system. out. println ("The I is/t" + I); <br/>}< br/> for (Int J = 0; j <10; j ++) {<br/> system. out. println ("the J is/t" + J); <br/>}< br/> // <br/> Public void getevent (runnable B) {<br/> synchronized (this) {<br/> This. B = B; <br/>}< br/>
Class B
Public Class B implements runnable {<br/> @ override <br/> Public void run () {<br/> // todo auto-generated method stub <br/> for (Int J = 0; j <10; j ++) {<br/> system. out. println ("the M is/t" + J); <br/>}< br/>}
B = new B (); <br/> A = new A (); <br/>. getevent (B); <br/>. start ();
The result is as follows:
The m is0 <br/> the M is1 <br/> the M is2 <br/> the M is3 <br/> the M is4 <br/> the M is5 <br /> the M is6 <br/> the M is7 <br/> the M is8 <br/> the M is9 <br/> The I is0 <br/> The I is1 <br/> The I is2 <br/> The I is3 <br/> The I is4 <br/> The I is5 <br/> The I is6 <br/> I is7 <br/> The I is8 <br/> The I is9 <br/> the J is0 <br/> the J is1 <br/> the J is2 <br/> The J is3 <br/> the J is4 <br/> the J is5 <br/> the J is6 <br/> the J is7 <br/> the J is8 <br/> the J is9 <br/>
B To thread
Public Class B extends thread {<br/> @ override <br/> Public void run () {<br/> // todo auto-generated method stub <br/> for (Int J = 0; j <10; j ++) {<br/> system. out. println ("the M is/t" + J); <br/>}< br/>}
Set B. Run --> B. Start ();
The result is that the M position is random ....
The I is0 <br/> The I is1 <br/> The I is2 <br/> The I is3 <br/> The I is4 <br/> The I is5 <br /> The I is6 <br/> the M is0 <br/> the M is1 <br/> the M is2 <br/> the M is3 <br/> the M is4 <br/> the M is5 <br/> the M is6 <br/> the M is7 <br/> the M is8 <br/> the M is9 <br/> I is7 <br/> The I is8 <br/> The I is9 <br/> the J is0 <br/> the J is1 <br/> the J is2 <br/> The J is3 <br/> the J is4 <br/> the J is5 <br/> the J is6 <br/> the J is7 <br/> the J is8 <br/> the J is9
Q: What is the difference between runnable and thread implementation? What is the difference between a. Run () and A. Start ??
Start a thread by calling the START () method of the thread class. The thread is in the ready state and is not running. This thread class then calls the method run () to complete its operation. Here the method run () is called the thread body, which contains the content of the thread to be executed, the run method ends and the thread ends, while the CPU runs other threads. If you use the run method directly, this is just a method, there is still only the main thread in the program-this thread, and there is only one program execution path, so the thread cannot be written.