java多線程——同步的前提

來源:互聯網
上載者:User

標籤:多線程   同步   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多線程——同步的前提

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.