標籤:blog 調度 str 共用資源 定義 需要 nbsp 多線程 邏輯
java: Thread 和 runnable線程類
Java有2種實現線程的方法:Thread類,Runnable介面。(其實Thread本身就是Runnable的子類)
Thread類,預設有run(), start()方法,繼承Thread類,需要實現run方法
Thread多線程,不能共用資源,保證資料的的統一(以商城商品數量,售票系統票的數量為例)
例如:
public class MyThread extends Thread {private String name; // 定義name屬性public MyThread(String name) {this.name = name;}public void run() {// 覆寫run()方法for (int i = 0; i < 50; i++) {// 表示迴圈10次System.out.println("Thread運行:" + name + ",i = " + i);}}}
實現1:
此種方法說明:mt1線程執行完後,才能執行mt2線程
public class ThreadDemo01 {public static void main(String[] args) {MyThread mt1 = new MyThread("線程A") ;MyThread mt2 = new MyThread("線程B") ;mt1.run() ;// 調用線程體mt2.run() ;// 調用線程體}}
實現2:
start()方法表示,調用系統底層方法,去搶佔cpu資源,誰先搶到,誰就能優先得到cpu的調度
public class ThreadDemo02 {public static void main(String[] args) {MyThread mt1 = new MyThread("線程A");MyThread mt2 = new MyThread("線程B");mt1.start(); // 調用線程體mt2.start(); // 調用線程體}}
Runnable:
public class MyThread implements Runnable { // 實現Runnable介面private String name; // 定義name屬性public MyThread(String name) {this.name = name;}public void run() {// 覆寫run()方法for (int i = 0; i < 50; i++) {// 表示迴圈10次System.out.println("Thread運行:" + name + ",i = " + i);}}}
實現子類:
public class RunnableDemo01 {public static void main(String[] args) {MyThread mt1 = new MyThread("線程A");MyThread mt2 = new MyThread("線程B");new Thread(mt1).start(); // 調用線程體new Thread(mt2).start(); // 調用線程體}}
推薦實現Runnable介面來使用多線程。
使用Runnable能實現資源共用,以商城/售票系統為例,售賣票
Thread例子:
public class MyThread extends Thread {// 繼承Thread類private int ticket = 5; // 一共才5張票public void run() {// 覆寫run()方法for (int i = 0; i < 50; i++) {// 表示迴圈10次if (this.ticket > 0) {System.out.println("賣票:ticket = " + this.ticket--);}}}}
實現子類:
此種方法:其實票一共只有5張,但是三個線程,每個線程都能買到5張票,這樣是不符合邏輯的
public class ThreadTicket {public static void main(String[] args) {MyThread mt1 = new MyThread(); // 一個線程MyThread mt2 = new MyThread(); // 一個線程MyThread mt3 = new MyThread(); // 一個線程mt1.start() ;// 開始賣票mt2.start() ;// 開始賣票mt3.start() ;// 開始賣票}}
實現方法二:
public class MyThread implements Runnable {// 實現Runnable介面private int ticket = 5; // 一共才5張票public void run() {// 覆寫run()方法for (int i = 0; i < 50; i++) {// 表示迴圈10次if (this.ticket > 0) {System.out.println("賣票:ticket = " + this.ticket--);}}}}
實現子類:
此方法,能實現線程內的資源共用,不會賣出多餘的票
public static void main(String[] args) {MyThread mt = new MyThread(); // 一個對象new Thread(mt).start() ;// 一個線程開始賣票new Thread(mt).start() ;//一個線程
new Thread(mt).start() ; // 一個線程開始賣票
}
}
java: Thread 和 runnable線程類