標籤:多線程 同步 java
同步的前提
- 必須要有兩個或以上的線程
- 必須是所有的線程使用同一個鎖
這樣保證同步中只能有一個線程在運行
在多安全執行緒問題設定同步時候注意
- 明確哪些代碼是多線程運行代碼
- 明確哪些是共用資料
- 明確多線程運行代碼中,哪些語句是操作共用資料的
同步的優點
解決了多線程的安全問題
同步的缺點
多個線程判斷鎖,較為耗費資源
class ThreadDemo1 { public static void main(String[] args) { Ticket tic = new Ticket(); Thread t1 = new Thread(tic); Thread t2 = new Thread(tic); Thread t3 = new Thread(tic); t1.start(); t2.start(); t3.start(); }}class Ticket implements Runnable { private int ticket = 500; Object obj = new Object(); public void run() { while (true) { synchronized (obj) { if (this.ticket > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " ... " + this.ticket); this.ticket--; } } } }}
class ThreadDemo2 { public static void main(String[] args) { Customer cus = new Customer(); Thread t1 = new Thread(cus); Thread t2 = new Thread(cus); t1.start(); t2.start(); }}/** * 一個銀行,有兩個客戶向銀行存錢,每個客戶有300元,每次均是存100元,每個人存3次 * */class Bank{ private int sumMoney; public synchronized void add(int money){ this.sumMoney = this.sumMoney + money; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("sumMoney = " + this.sumMoney); }}class Customer implements Runnable{ private Bank bank = new Bank(); public void run(){ for (int i = 1; i<=3; i++){ bank.add(100); } }}
java多線程——同步的前提