MENU

多线程举例——加减运算

• November 21, 2020 • java高级特性

实现加法减法,加一次,减一次,不可连续加,不可连续减,典型的生产者与消费者模型

/**
 * 减线程
 * */
class Sub implements Runnable{
    private Resource resource;
    public Sub(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run(){
        for (int i = 0; i < 25; i++) {
            this.resource.sub();
        }
    }
}

/**
 * 加线程
 * */
class Add implements Runnable{
    private Resource resource;
    public Add(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run(){
        for (int i = 0; i < 25; i++) {
            this.resource.add();
        }
    }
}

/**
 * 数据源
 *
 * */
class Resource{
    private int num = 0;
    /**
     * true:可加不可减
     * false:可减不可加
     * */
    private boolean flag = true;
    
    /** 加操作 */
    public synchronized void add(){
        if(!this.flag){
            try {
                super.wait(); // 为false 需要等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.num ++;
        System.out.println(Thread.currentThread().getName() + "进行了加法操作, num = " + this.num);
        this.flag = false;
        // 加之后进行唤醒
        super.notify();
    }
    
    public synchronized void sub(){
        if(this.flag){
            try {
                super.wait(); // 为true需要等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.num --;
        System.out.println(Thread.currentThread().getName() + "进行了减法操作, num = " + this.num);
        this.flag = true;
        // 减之后进行唤醒
        super.notify();
    }
}

/**
 * @author Administrator
 */
public class Main {
    public static void main(String[] args) {
        Resource resource = new Resource();
        Add add = new Add(resource);
        Sub sub = new Sub(resource);
        new Thread(add, "加法线程").start();
        new Thread(sub, "减法线程").start();
    }
}

解决同步问题:
synchornized关键字
解决重复问题:
设定标志flag,Object类的唤醒与等待机制


代码编译器:IntelliJ IDEA 20.01

Archives QR Code Tip
QR Code for this page
Tipping QR Code