1. 程式人生 > >java多執行緒--簡易使用同步鎖實現一對一交替列印

java多執行緒--簡易使用同步鎖實現一對一交替列印

  • 一、本例需要分析的地方不多,只需要使用一個同步鎖+一個計數器就能搞定,直接奉送原始碼吧:
package com.example.liuxiaobing.statemodel.mutil_thread.onebyoneprint;

/**
 * Created by liuxiaobing
 * Date on 2018/9/23
 * Copyright 2013 - 2018 QianTuo Inc. All Rights Reserved
 * Desc: 2個執行緒交替列印
 */

public class Print  {

    private int count = 1;      //列印併發數


    public synchronized void print(String name) throws InterruptedException {

        while(count <= 0){
            wait();
        }
        System.out.println("20---------:當前執行緒:"+Thread.currentThread().getName() + " 列印東西:"+name);
        count --;
        notifyAll();
        count ++;
    }
}

  • 二、測試用的列印執行緒:
package com.example.liuxiaobing.statemodel.mutil_thread.onebyoneprint;

/**
 * Created by liuxiaobing
 * Date on 2018/9/23
 * Copyright 2013 - 2018 QianTuo Inc. All Rights Reserved
 * Desc:
 */

public class PrintThread extends Thread {

    private boolean isStop = false;
    private Print mPrint;

    public PrintThread(String name,Print print){
        setName(name);
        mPrint = print;
    }

    @Override
    public void run() {
        super.run();
        while (!isStop){
            try {
                Thread.sleep(1000);
                mPrint.print("列印簡歷");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 三、測試例子
private void testThreadPrintOneByOne(){
       Print print = new Print();
       PrintThread printThread1 = new PrintThread("1",print);
       PrintThread printThread2 = new PrintThread("2",print);
       printThread1.start();
       printThread2.start();



   }