多线程基础-实现多线程的两种方式(二)
生活随笔
收集整理的這篇文章主要介紹了
多线程基础-实现多线程的两种方式(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現多線程的兩種方式:
1.實現Runnable
public interface Runnable {public abstract void run(); }// RunnableTest.java 源碼 class MyThread implements Runnable{ private int ticket=10; public void run(){for(int i=0;i<20;i++){ if(this.ticket>0){System.out.println(Thread.currentThread().getName()+" 賣票:ticket"+this.ticket--);}}} }; public class RunnableTest { public static void main(String[] args) { MyThread mt=new MyThread();// 啟動3個線程t1,t2,t3(它們共用一個Runnable對象),這3個線程一共賣10張票!Thread t1=new Thread(mt);Thread t2=new Thread(mt);Thread t3=new Thread(mt);t1.start();t2.start();t3.start();} }2.繼承Thread
public class Thread implements Runnable {}// ThreadTest.java 源碼 class MyThread extends Thread{ private int ticket=10; public void run(){for(int i=0;i<20;i++){ if(this.ticket>0){System.out.println(this.getName()+" 賣票:ticket"+this.ticket--);}}} };public class ThreadTest { public static void main(String[] args) { // 啟動3個線程t1,t2,t3;每個線程各賣10張票!MyThread t1=new MyThread();MyThread t2=new MyThread();MyThread t3=new MyThread();t1.start();t2.start();t3.start();} }總結:Thread是一個類,而Runnable是一個接口,因此實現Runnable接口具有天然的擴展性優(yōu)勢,而且Thread有一個構造函數參數是Runnable接口的,可以共享資源。
總結
以上是生活随笔為你收集整理的多线程基础-实现多线程的两种方式(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多线程基础-基本概念(一)
- 下一篇: 多线程基础-常用线程方法(三)