您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關Java如何在不同線程中實現運行,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
具體如下:
start()方法開始為一個線程分配CPU時間,這導致對run()方法的調用。
代碼1
package Threads; /** * Created by Frank */ public class ThreadsDemo1 extends Thread { private String msg; private int count; public ThreadsDemo1(final String msg, int n) { this.msg = msg; count = n; setName(msg + " runner Thread"); } public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } public static void main(String[] args) { new ThreadsDemo1("Hello from X", 10).start(); new ThreadsDemo1("Hello from Y", 15).start(); } }
代碼2:
package Threads; /** * Created by Frank */ public class ThreadsDemo2 implements Runnable { private String msg; private Thread t; private int count; public static void main(String[] args) { new ThreadsDemo2("Hello from X", 10); new ThreadsDemo2("Hello from Y", 15); } public ThreadsDemo2(String m, int n) { this.msg = m; count = n; t = new Thread(this); t.setName(msg + "runner Thread"); t.start(); } public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } }
代碼3:
package Threads; /** * Created by Frank */ public class ThreadsDemo3 { private int count; public static void main(String[] args) { new ThreadsDemo3("Hello from X", 10); new ThreadsDemo3("Hello from Y", 15); } public ThreadsDemo3(final String msg, int n) { this.count = n; Thread t = new Thread(new Runnable() { public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } }); t.setName(msg + " runner Thread"); t.start(); } }
eclipse運行結果如下:
上述就是小編為大家分享的Java如何在不同線程中實現運行了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。