Java创建线程的三种方式
1.继承Runnable接口
package test; class RunnableDemo implements Runnable{ private Thread t; private String threadName; RunnableDemo(String name){ threadName=name; System.out.println("Creating "+name); } public void run(){ System.out.println("Running "+threadName); try{ for(int i=4;i>0;i--){ System.out.println("Thread: "+threadName+" "+i); Thread.sleep(50); } } catch(InterruptedException e){ System.out.println("Thread "+threadName+" Excepted"); } System.out.println("Thread "+threadName+" Exiting"); } public void start(){ System.out.println("Starting "+threadName); if(t==null){ t=new Thread(this,threadName); t.start(); } } } public class HelloWorld { public static void main(String []args) { RunnableDemo R1=new RunnableDemo("thread1"); R1.start(); RunnableDemo R2=new RunnableDemo("thread2"); R2.start(); } }
2.继承Thread类
package test; class ThreadDemo extends Thread{ private Thread t; private String threadName; ThreadDemo(String name){ threadName=name; System.out.println("Creating "+name); } public void run(){ System.out.println("Running "+threadName); try{ for(int i=4;i>0;i--){ System.out.println("Thread: "+threadName+" "+i); Thread.sleep(50); } } catch(InterruptedException e){ System.out.println("Thread "+threadName+" Excepted"); } System.out.println("Thread "+threadName+" Exiting"); } public void start(){ System.out.println("Starting "+threadName); if(t==null){ t=new Thread(this,threadName); t.start(); } } } public class HelloWorld2 { public static void main(String []args) { ThreadDemo T1=new ThreadDemo("thread1"); T1.start(); ThreadDemo T2=new ThreadDemo("thread2"); T2.start(); } }
3.通过 Callable 和 Future 创建线程