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 boolean printing = false;


    public synchronized void print(String name) throws InterruptedException {

        while(!printing){
            wait();
        }
        System.out.println("20---------:当前线程:"+Thread.currentThread().getName() + " 打印东西:"+name);
        printing = false;
        notifyAll();
    }


    public synchronized void print2(String name) throws InterruptedException {

        while(printing){
            wait();
        }
        System.out.println("31---------:当前线程:"+Thread.currentThread().getName() + " 打印东西:"+name);
        printing = true;
        notifyAll();

    }
}

  • 二、测试用的打印线程:
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(100);
                mPrint.print("打印简历");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

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 Print2Thread extends Thread {

    private boolean isStop = false;
    private Print mPrint;

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

    @Override
    public void run() {
        super.run();
        while (!isStop){
            try {
                Thread.sleep(100);
                mPrint.print2("打印ppt");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 三、测试例子
   private void testThreadPrintOneByOne(){
       Print print = new Print();
       PrintThread printThread1 = new PrintThread("1",print);
       Print2Thread printThread2 = new Print2Thread("2",print);

       printThread1.start();
       printThread2.start();



   }

java多线程--简易使用同步锁实现一对一交替打印_第1张图片

你可能感兴趣的:(java并发编程)