線程:每一個任務稱為一個線程,線程不能獨立的存在,它必須是進程的一部分
單線程:般常見的Java應用程序都是單線程的,比如運行helloworld的程序時,會啟動jvm進程,然後運行main方法產生線程,main方法也被稱為主線程。
多線程:同時運行一個以上線程的程序稱為多線程程序,多線程能滿足程序員編寫高效率的程序來達到充分利用CPU 的目的。
單線程代碼例子:
public class SingleThread {public static void main(String[] args){Thread thread = Thread.currentThread(); //獲取當前運行的線程對象thread.setName("單線程"); //線程重命名System.out.println(thread.getName()+"正在運行");for(int i=0;i<10;i++){System.out.println("線程正在休眠:"+i);try {thread.sleep(1000); //線程休眠,延遲一秒} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("線程出錯");}}}}多線程代碼例子:
注意:多線程有兩種實現方式,一種是繼承Thread類,另一種是實現Runnable接口。
繼承Thread類實現多線程
public class TestThread {public static void main(String[] args){ Thread t1 = new ExtendThread("t1",1000); //使用上轉對象創建線程,並構造線程名字和線程休眠時間Thread t2 = new ExtendThread("t2",2000); Thread t3 = new ExtendThread("t3",3000); t1.start(); //啟動線程並調用run方法t2.start(); t3.start();}}class ExtendThread extends Thread{ //繼承Thread的類String name;int time;public ExtendThread(String name, int time) { //構造線程名字和休眠時間this.name=name;this.time=time;}public void run(){ //重寫Thread類的run方法try{sleep(time); //所有線程加入休眠}catch(InterruptedExceptione){e.printStackTrace();System.out.println("線程中斷異常");}System.out.println("名稱為:"+name+",線程休眠:"+time+"毫秒"); }}實現Runnable接口的多線程
public class RunnableThread {public static void main(String[] args){Runnable r1=new ImplRunnable("r1",1000); //Runnable接口必須依托Thread類才能創建線程Thread t1=new Thread(r1); //Runnable並不能調用start()方法,因為不是線程,所以要用Thread類加入線程Runnable r2=new ImplRunnable("r2",2000);Thread t2=new Thread(r2);Runnable r3=new ImplRunnable("r3",3000);Thread t3=new Thread(r3);t1.start(); //啟動線程並調用run方法t2.start();t3.start();}}class ImplRunnable implements Runnable{ //繼承Runnable接口的類String name;int time;public ImplRunnable(String name, int time) { //構造線程名字和休眠時間this.name = name;this.time = time;}@Overridepublic void run() { //實現Runnable的run方法try{Thread.sleep(time); //所有線程加入休眠}catch(InterruptedException e){e.printStackTrace();System.out.println("線程中斷異常");}System.out.println("名稱為:"+name+",線程休眠:"+time+"毫秒");}}說明:Thread類實際上也是實現了Runnable接口的類。
實現Runnable接口比繼承Thread類所具有的優勢