總
1,如果每個線程執行的代碼相同,可以使用同一個Runnable對象,這個Runnable對象中有那個共享數據,例如,賣票系統就可以這么做。
2,如果每個線程執行的代碼不同,這時候需要用不同的Runnable對象,例如,設計4個線程。其中兩個線程每次對j增加1,另外兩個線程對j每次減1,銀行存取款
每個線程執行的代碼相同,可以使用同一個Runnable對象
public class RunnalbleTest2 implements Runnable { private int threadCnt = 10; @Override public void run() { while (true) { if (threadCnt > 0) { System.out.println(Thread.currentThread().getName() + " 剩余個數 " + threadCnt); threadCnt--; try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } public static void main(String[] args) { RunnalbleTest2 runnalbleTest2 = new RunnalbleTest2(); new Thread(runnalbleTest2).start(); new Thread(runnalbleTest2).start(); } }
結果
Thread-0 剩余個數 10 Thread-1 剩余個數 10 Thread-0 剩余個數 8 Thread-1 剩余個數 7 Thread-0 剩余個數 6 Thread-1 剩余個數 5 Thread-0 剩余個數 4 Thread-1 剩余個數 3 Thread-0 剩余個數 2 Thread-1 剩余個數 1
每個線程執行的代碼不同,用不同的Runnable對象
#
public class Acount { private int money; Acount(int money) { this.money = money; } public synchronized void getMoney(int money) { while (this.money < money) { System.out.println("余額不足"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } this.money -= money; System.out.println("取出" + money + ",還剩" + this.money); } public synchronized void setMoney(int money) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } this.money += money; System.out.println("新存入" + money + ",總額:" + this.money); notify(); } public static void main(String[] args) { Acount acount = new Acount(0); Bank bank = new Bank(acount); Consumer consumer = new Consumer(acount); new Thread(bank).start(); new Thread(consumer).start(); } }
#
import java.util.Random; public class Bank implements Runnable{ Acount acount; public Bank(Acount acount) { this.acount = acount; } @Override public void run() { while(true) { int random = (int)(Math.random() * 1000); acount.setMoney(random); } } }
#
public class Consumer implements Runnable{ Acount acount; Consumer(Acount acount) { this.acount = acount; } @Override public void run() { while (true) { int random = (int)(Math.random() * 1000); acount.getMoney(random); } } }
結果
新存入442,總額:442 余額不足 新存入196,總額:638 新存入815,總額:1453 取出534,還剩919 新存入402,總額:1321 取出719,還剩602 取出11,還剩591 ....
