java 多線程Thread與runnable的區(qū)別
java 多線程Thread與runnable的區(qū)別
java中實現(xiàn)多線程的方法有兩種:繼承Thread類和實現(xiàn)runnable接口
1,繼承Thread類,重寫父類run()方法
public class thread1 extends Thread { public void run() { for (int i = 0; i < 10000; i++) { System.out.println("我是線程"+this.getId()); } } public static void main(String[] args) { thread1 th1 = new thread1(); thread1 th2 = new thread1(); th1.run(); th2.run(); } }
run()方法只是普通的方法,是順序執(zhí)行的,即th1.run()執(zhí)行完成后才執(zhí)行th2.run(),這樣寫只用一個主線程。多線程就失去了意義,所以應(yīng)該用start()方法來啟動線程,start()方法會自動調(diào)用run()方法。上述代碼改為:
public class thread1 extends Thread { public void run() { for (int i = 0; i < 10000; i++) { System.out.println("我是線程"+this.getId()); } } public static void main(String[] args) { thread1 th1 = new thread1(); thread1 th2 = new thread1(); th1.start(); th2.start(); } }
通過start()方法啟動一個新的線程。這樣不管th1.start()調(diào)用的run()方法是否執(zhí)行完,都繼續(xù)執(zhí)行th2.start()如果下面有別的代碼也同樣不需要等待th2.start()執(zhí)行完成,而繼續(xù)執(zhí)行。(輸出的線程id是無規(guī)則交替輸出的)
2,實現(xiàn)runnable接口
public class thread2 implements Runnable { public String ThreadName; public thread2(String tName){ ThreadName = tName; } public void run() { for (int i = 0; i < 10000; i++) { System.out.println(ThreadName); } } public static void main(String[] args) { thread2 th1 = new thread2("線程A"); thread2 th2 = new thread2("Thread-B"); th1.run(); th2.run(); } }
和Thread的run方法一樣Runnable的run只是普通方法,在main方法中th2.run()必須等待th1.run()執(zhí)行完成后才能執(zhí)行,程序只用一個線程。要多線程的目的,也要通過Thread的start()方法(runnable是沒有start方法)。上述代碼修改為:
public class thread2 implements Runnable { public String ThreadName; public thread2(String tName){ ThreadName = tName; } public void run() { for (int i = 0; i < 10000; i++) { System.out.println(ThreadName); } } public static void main(String[] args) { thread2 th1 = new thread2("線程A"); thread2 th2 = new thread2("Thread-B"); Thread myth1 = new Thread(th1); Thread myth2 = new Thread(th2); myth1.start(); myth2.start(); } }
總結(jié):實現(xiàn)java多線程的2種方式,runable是接口,thread是類,runnable只提供一個run方法,建議使用runable實現(xiàn) java多線程,不管如何,最終都需要通過thread.start()來使線程處于可運行狀態(tài)。
以上就是關(guān)于java多線程的實例詳解,如有疑問請留言或者到本站社區(qū)交流討論,本站關(guān)于線程的文章還有很多,希望大家搜索查閱,大家共同進步!
相關(guān)文章
Spring?Boot之Validation自定義實現(xiàn)方式的總結(jié)
這篇文章主要介紹了Spring?Boot之Validation自定義實現(xiàn)方式的總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07Java內(nèi)存之happens-before和重排序
在JMM(Java內(nèi)存模型)中,如果一個操作執(zhí)行的結(jié)果需要對另一個操作可見,那么這兩個操作之間必須存在happens-before關(guān)系。下面小編來簡單介紹一下2019-05-05Java Web項目中實現(xiàn)文件下載功能的實例教程
這篇文章主要介紹了Java Web項目中實現(xiàn)文件下載功能的實例教程,分別講解了通過超鏈接實現(xiàn)下載以及通過Servlet程序?qū)崿F(xiàn)下載的方式,需要的朋友可以參考下2016-05-05