1, class structure, first there are two classes, one is the test class main, one is the thread class Mythread.
2, MyThread
Package Com.test.thread;import Java.lang.management.threadinfo;public class MyThread implements Runnable {String name= Null MyThread (String name) {this.name=name;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {System.out.println (name+ ": Output result ...");}}
Main
Package Com.test.thread;public class Main {/** * @param args */public static void Main (string[] args) {//TODO Auto-genera Ted Method Stubmythread mya=new MyThread ("Thread A"); Thread Testa=new thread (mya); Testa.start (); MyThread myb=new MyThread ("thread B"); Thread testb=new thread (MYB); Testb.start ();}}
3. Output results
4. Advanced version
With the above is not good to explain the problem, because the running speed is relatively fast, do not see the two alternate running, if the thread in the process of sleep function, let the thread run for a period of time to hibernate, and then re-restore will be more intuitive, change the code as follows.
Package Com.test.thread;import Java.lang.management.threadinfo;public class MyThread implements Runnable {String name= Null MyThread (String name) {this.name=name;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {try {thread.sleep ()} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (name+ ": Output result ...");}}
5. Operation Result
Analysis of the usage of runnable in Java