Multi-threaded Code implementation:
Method 2: Implement the Runnable interface
Steps:
A: Custom class myrunnable Implementation Runnable interface
B: Rewrite the Run () method
C: Create an object of the Myrunnable class
D: Create the object of the thread class and pass the C-Step object as a construction parameter (2 methods)
A:thread (Runnable target)
B:thread (Runnable target, String name)
Benefits of Mode 2:
A: Because Java inherits in a single inheritance, mode 2 avoids the limitations of Java single inheritance
B: Suitable for a number of the same program code to deal with the same resource situation, the thread with the program code, data effectively separated, better reflect the object-oriented design ideas
First look at the code implementation of mode 2, and then explain the benefits B
Create a custom class by performing steps a and B first
1 Public classMyrunnableImplements Runnable {2 3 Public voidrun () {4 for(intx = 1; x < 100; X + +){5System.out.println (Thread.CurrentThread (). GetName () + "--" +x);6 }7 8 }9}
Then follow steps c and D to create a test class
1 Public classMyrunnabledemo {2 3 Public Static voidMain (string[] args) {4 //to create an object of the Myrunnable class5Myrunnable Mr =Newmyrunnable ();6 7 //creates an object of the thread class and passes the C-step object as a construction parameter \8 /* 9 //mode 1:thread (Runnable target)ten thread t1 = new Thread (MR); one thread t2 = new Thread (MR); //To the thread named the T1.setname ("Husky"); t2.setname ("Samoyed"); the - */ // mode 2:thread (Runnable target, String name), Thread t1 = new T Hread (MR, "husky"); Thread t2 = New thread (MR, "Samoyed"); - + //Execution Thread A T1.start (); at T2.start (); - } - -}
Through the code, you can find. In the test class, only one object of the Myrunnable class is created, and in mode 1, several threads are required to create several objects. (The same program code in the case of the thread)
So, the benefits of Mode 2 B are reflected here.
How Java 22-9 Multi-thread code is implemented 2