Java Tread multithreading (1) Runnable interface implementation
This article demonstrates how to implement the Runnable interface with Tread multithreading and briefly explains why this method is used to create threads.
I. How to Create thread 2:
1) inherit the Thread class to implement multithreading. See my previous article: Java Tread multithreading (0) A simple multi-threaded instance;
2) The second method is to implement the Runnable interface and create a new thread.
2. Why are there two ways to create a thread?
① The main reason is that method 1 cannot meet our needs, so method 2 is generated );
② The reason cannot meet the requirements: the main reason is that Java can only have single inheritance. If a class Student must be inherited from the Person class, we need to implement multiple threads for some content in Student, isn't that a conflict? (Because method 1 must inherit from Thread to implement multithreading .), So here we introduce the Runnable method: to implement the Runnable interface to achieve the effect of multithreading, we recommend that you use the second method at ordinary times, that is, the method in this article.
3. A small Demo
Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {private int x = 0; // 2. overwrite the run method in the Runnable interface // store the thread code in the run public void run () {while (x <= 100) System. out. println (Runnable: + (x ++) ;}} public class CRunableDemo1 {public static void main (String [] args) {RunDemo1 r = new RunDemo1 (); // 3. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r); // 4. use start to enable thread t1.start (); t2.start ();}}
The running result shows: (0-10 is printed here. Note: There are no duplicates)
Based on the above running results, we will try to compare the following code (defining x as a local variable ):
Package thread. runable1.qdj; // 1. define class implementation Runnable interface class RunDemo1 implements Runnable {// private int x = 0; // 2. override the run method in the Runnable interface // store the thread code in the run public void run () {for (int x = 0; x <= 3; ++ x) System. out. println (Runnable: + x) ;}} public class CRunableDemo1 {public static void main (String [] args) {RunDemo1 r = new RunDemo1 (); // 3. create a Thread object through the Thread class, and take the subclass object of the Runnable interface as the parameter Thread t1 = new Thread (r); Thread t2 = new Thread (r); // 4. use start to enable thread t1.start (); t2.start ();}}
The running result is displayed (I printed it twice and found it ?) :
Compared with the two situations, this actually illustrates a problem:
Conclusion: Each thread contains a local variable.
References: Lecture on Java video Bi Xiangdong
Address: http://blog.csdn.net/qingdujun/article/details/39347245