java執行緒兩種實現方式的區別,你所不知道的小細節
阿新 • • 發佈:2019-02-15
/* * 建立執行緒時要繼承Runnable介面 * 不要把寶貴的單繼承機會佔有掉 * 兩種方式有點不用,實現Runnable * 介面時多個執行緒中執行一個 * Runnable介面實現類時,run方法資源共享 * 而繼承Thread時,run方法資源是 * 不能共享的! */ public class Test_Runnable_Thread { public static void main(String[] args) { /* * 下面的程式碼執行400次列印語句 */ SubThread subT1 = new SubThread(); SubThread subT2 = new SubThread(); SubThread subT3 = new SubThread(); SubThread subT4 = new SubThread(); subT1.start(); subT2.start(); subT3.start(); subT4.start(); /* * 下面的程式碼執行100次列印語句 */ SubRunnable subR = new SubRunnable(); Thread th1 = new Thread(subR); Thread th2 = new Thread(subR); Thread th3 = new Thread(subR); Thread th4 = new Thread(subR); th1.start(); th2.start(); th3.start(); th4.start(); } } class SubRunnable implements Runnable { private int id = 100; @Override public void run() { while (true) { // 請自動關閉死迴圈,為了效果設定死迴圈 dos視窗中ctrl+c關閉 if (id > 0) { System.out.println(Thread.currentThread().getName() + "run..." + id--); } } } } class SubThread extends Thread { private int id = 100; @Override public void run() { while (true) { // 請自動關閉死迴圈,為了效果設定死迴圈 dos視窗中ctrl+c關閉 if (id > 0) { System.out.println(Thread.currentThread().getName() + "run..." + id--); } } } }