java 線程同步1 (傳統方法)

來源:互聯網
上載者:User
package com.thread;/** * 線程同步 ,子線程執行一次,主線程後在執行一次 * 大家輪流執行 *  * @author sky * */public class TraditionThread {public static void main(String[] args) {new TraditionThread().init();}public void init (){final Business business = new Business();// 直接重載父類的方法    子線程new Thread(){@Overridepublic void run() {for (int i = 1; i <=3; i++) {business.sub();}}}.start();// 主線程for (int i = 1; i <=3; i++) {business.main();}}class Business {private boolean isShouldSub = true; // true:子線程開始執行, false:主線程開始執行public synchronized void sub (){if (!isShouldSub){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}  for (int i = 1; i <=2; i++) {  System.out.println("print sub ");}isShouldSub = false;this.notify();     }public synchronized void main (){ // true 等待 if (isShouldSub){ try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }for (int i = 1; i <= 3; i++) {System.out.println("main");}// 執行完了之後,通知子線程執行isShouldSub = true;this.notify();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.