On the previous blog we introduced some basic concepts, processes, threads, concurrency. Let's start by writing the first multithreaded program.
two ways: first, the realization of Runnable interface, Basic Thread class.
first, to achieve Runnable Interface
Package Com.tgb.klx.thread;public class Hello1 implements Runnable {public hello1 () {}public hello1 (String name) {this.na me = name;} public void Run () {for (int i = 0; i < 5; i++) {System.out.println (name + "Run " + i);}} public static void Main (string[] args) {hello1 H1 = new Hello1 ("Thread A"); Thread demo1 = new Thread (h1), hello1 h2 = new Hello1 ("Thread B"); Thread Demo2 = new Thread (H2);d Emo1.start ();d Emo2.start ();} private String name;}
Operation Result:
second, based on Thread class
Package Com.tgb.klx.thread;public class Hello2 extends Thread {public Hello2 () {}public Hello2 (String name) {this.name = n Ame;} public void Run () {for (int i = 0; i < 5; i++) {System.out.println (name + "Run " + i);}} public static void Main (string[] args) {Hello2 H1 = new Hello2 ("A"); Hello2 h2 = new Hello2 ("B"); H1.start (); H2.start ();} private String name;}
Operation Result:
The way to implement the Runnable interface, you need to create a thread class, the implementation of the Runnable class instance as a parameter, to start a thread, if the direct call to runnable the Run method is not different from calling the normal class method, will not create a new thread.
The thread class implements the Runnable interface, the thread class also has the Run method, the call thread's Run method also does not create a new thread, and calls the ordinary method no difference, so everyone in the use of multi-threading must pay attention to.
Summarize:
Both of these methods can be achieved, the specific choice of which method is determined according to the situation. Java does not support multiple inheritance, so the way to implement the Runnable interface may be more flexible.
Java concurrent Programming-multi-thread HelloWorld