多線程兩種實現方式的區別
阿新 • • 發佈:2017-09-02
http [] tick 避免 main 單繼承 style 區別 tar
請解釋Thread類與Runnable接口實現多線程的區別?(請解釋多線程兩種實現方式的區別?)
1. Thread類時Runnable接口的子類,使用Runnable接口實現多線程可以避免單繼承局限!
2. Runnable接口實現的多線程可以比Thread類實現的多線程更加清楚的描述數據共享的概念!
請寫出多線程兩種實現操作?(寫出Thread類繼承的方式和Runnable接口實現的方式代碼!)
實現Thread類:
類似於代理設計模式!
class MyThread extends Thread { // 這是一個多線程的操作類 private int ticket = 10;public void run() { // 重寫run()方法,作為線程的主體操作方法 for(int i=0;i<100;i++){ if(this.ticket > 0){ System.out.println("賣票,ticket="+this.ticket--); } } } } public class Demo_Thread { // 主類 public static void main(String[] args) { MyThread mt= new MyThread(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } }
實現Runnable接口:
class MyRunnable implements Runnable { // 這是一個多線程的操作類 private int ticket = 10; public void run() { for(int i=0;i<100;i++){ if(this.ticket>0){ System.out.println("賣票,ticket="+this.ticket--); } } } } public class Demo_Runnable { // 主類 public static void main(String[] args) { MyThread mt = new MyThread(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } }
多線程兩種實現方式的區別