/** * 線程類 * @author * @date 2018/7/31 16:04 */ public class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; } @Override public void run() { for (int i = 0; i < 8; i++) { System.out.println("name=" +name+":"+ i); } } }
/** * 測試類 * @author limh * @date 2018/7/31 16:07 */ public class TestMain { public static void main(String[] args){ //新建線程 MyThread t1 = new MyThread("A"); MyThread t2 = new MyThread("B"); //啓動線程 t1.start(); t2.start(); } }
若是一個類繼承Thread,則不適合資源共享。可是若是實現了Runnable接口的話,則很容易的實現資源共享。java
/** * Runnable類 * @author * @date 2018/7/31 16:15 */ public class MyThread1 implements Runnable { private int ticket = 10; @Override //公共資源,要在run方法以前加上synchronized,要否則會出現搶資源的狀況 public synchronized void run() { for (int i=0;i<10;i++){ if (this.ticket > 0){ System.out.println("賣票:ticket"+this.ticket--); } } } }
/** * 測試類 * @author limh * @date 2018/7/31 16:07 */ public class TestMain { public static void main(String[] args){ //測試Runnable MyThread1 t1 = new MyThread1(); //同一個t1,資源共享。若是不是同一個,則達不到該效果 new Thread(t1).start(); new Thread(t1).start(); new Thread(t1).start(); } }
實現Runnable接口比繼承Thread類所具備的優點:ide