In a manner Runable interface to create a thread has a big advantage over inheritance Thread class, because the class is not multiple inheritance, that is, a class can only inherit a class, if the class has inherited a class, can not be achieved multithreading , but it can be achieved through a multi-threaded manner Runable interface.
1, Runnable multi-threaded
package pers.zhb.runnable; public class MyThread implements Runnable{ public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName()+":正在执行!"+i); } } }
pers.zhb.runnable Package; public class RunnableDemo { public static void main (String [] args) { the MyThread MT = new new the MyThread (); Thread T2 = new new Thread (MT); // also essentially Thread class implements Runnable interface , but the method is empty Run t2.start (); for ( int I = 0 ; I < 20 is ; I ++ ) { the System. OUT .println ( " main function thread! " + I); } . the System OUT .println ( " the main function execution is over ."); } }
2, using the join () method
The main thread starts running after the end of the child thread running.
package pers.zhb.runnable; public class MyThread implements Runnable{ public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName()+":正在执行!"+i); } } }
package pers.zhb.runnable; public class RunnableDemo { public static void main(String[] args) throws InterruptedException { MyThread mt = new MyThread(); Thread t1 = new Thread(mt); t1.start(); t1.join(); for (int i = 0; i < 20; i++) { System.out.println("主函数线程!" + i); } System.out.println(" The main function performed ended " ); } }