天天看點

java多線程同步和通信

java多線程之間互斥的一種方式是使用sychronized來修改被多線程通路的代碼;

而線程之間進行同步有序的進行時,可以使用wait(),notify()方法來實作

例如:子線程運作10次,主線程運作100次,子線程運作10次,主線程在運作100次,循環共50次。

package com.thread;

/**
 * @Author madongxu
 * @Date 2018-04-23
 *
 * 線程同步和互斥
 */
public class TraditionalSynchronizedDemo {

    public static void main(String[] args) {

        final Business business = new Business();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i =;i<=;i++){
                    business.sub(i);
                }
            }
        });
        thread.start();

        for(int j =;j<=;j++){
            business.main(j);
        }
    }

   static class Business{
        //子線程先執行
        boolean subShould = true;

        public synchronized void  sub(int i ){
            while (!subShould){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //執行子線程邏輯
            for (int a = ; a < ;a++){
                System.out.println("sub thread run.."+a+"loop of"+i);
            }

            subShould=false;
            this.notify();
        }


        public synchronized void main(int i){
            while(subShould){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //執行住線程邏輯
            for(int b = ;b < ;b++){

                System.out.println("main thread run.."+b+" loop of "+i);

            }
            subShould=true;
            this.notify();
        }
    }
}
           

繼續閱讀