Java 多线程 --- 按序打印

给你一个类:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

三个不同的线程 A、B、C 将会共用一个 Foo 实例。

  • 线程 A 将会调用 first() 方法
  • 线程 B 将会调用 second() 方法
  • 线程 C 将会调用 third() 方法
  • 请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

方法1 — 控制变量

class Foo {

    int order = 1;

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        order = 2;
    }

    public void second(Runnable printSecond) throws InterruptedException {
        while (order != 2) {}
        printSecond.run();
        order = 3;
    }

    public void third(Runnable printThird) throws InterruptedException {
        while (order != 3) {}
        printThird.run();
    }
}
  • 上面方法会超时
  • 原因是没有实现可见性, 也就是线程没有立即得到order更新后的值, 所以一直卡在while循环里, 导致超时
  • 比如线程1将order修改为2之后, 线程2没有得到这个更新, 导致一致卡在自己的while循环中
  • 关于可见性: 线程在执行的时候会将主内存中的变量拷贝一份到工作内存中,之后线程的运行只与工作内存打交道
    在这里插入图片描述

使用volatile关键字优化

  • volatile关键字可以保证可见性, 也就是对变量的更新可以立即被其他线程所捕获
class Foo {

    volatile int order = 1;

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        order = 2;
    }

    public void second(Runnable printSecond) throws InterruptedException {
        while (order != 2) {}
        printSecond.run();
        order = 3;
    }

    public void third(Runnable printThird) throws InterruptedException {
        while (order != 3) {}
        printThird.run();
    }
}
  • 以上实现方法还有缺点, 就是当一个线程执行时, 其他线程会不断的执行while循环, 消耗CPU的资源
  • 可以通过synchronized + wait + notifyAll的方式解决

方法2 — synchronized + wait + notifyAll

  • 使用wait可以让目前还不能允许的线程进入等待阻塞状态, 直到正在允许的线程完成任务之后调用notifyAll唤醒.
  • 当其他线程被唤醒后, 会竞争锁
  • 当一个线程拿到锁之后, 通过flag检查是否该自己运行, 如果不该自己运行则又进入等待阻塞状态, 并且释放锁
public class Foo {
    
    private int flag = 0;
    //声明一个objetc作为锁
    private Object lock = new Object();
    public Foo() {

    }
    public void first(Runnable printFirst) throws InterruptedException {
        synchronized (lock){
            while( flag != 0){
                //还没有轮到自己运行, 进入阻塞状态. 
                lock.wait();
            }
            printFirst.run();
            flag = 1;
            //唤醒其他在阻塞状态的线程
            lock.notifyAll();
        }
    }
    public void second(Runnable printSecond) throws InterruptedException {
        synchronized (lock){
            while (flag != 1){
                lock.wait();
            }
            printSecond.run();
            flag = 2;
            lock.notifyAll();
        }
    }
    public void third(Runnable printThird) throws InterruptedException {
        synchronized (lock){
            while (flag != 2){
                lock.wait();
            }
            printThird.run();
            flag = 0;
            lock.notifyAll();
        }
    }
}

方法3 — 信号量

  • 也可以使用信号量控制线程的执行顺序
class Foo {
    //控制第一个和第二个线程的顺序,初始信号量为0
    private final Semaphore first_to_second =new Semaphore(0);
    //控制第二个和第三个线程的顺序, 初始信号量为0
    private final Semaphore second_to_third =new Semaphore(0);

    public Foo() {
		
    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        first_to_second.release();//增加信号量, first_to_second的信号量变为0, 将线程2唤起
    }

    public void second(Runnable printSecond) throws InterruptedException {
         //尝试获取信号量, first_to_second 初始为0, count--, 信号量变为-1, 线程2被放入blocking queue
        first_to_second.acquire();
        printSecond.run();
        //增加信号量, second_to_third的信号量变为0, 将线程3唤起
        second_to_third.release();
    }

    public void third(Runnable printThird) throws InterruptedException {
         //尝试获取信号量, second_to_third 初始为0, count--, 信号量变为-1, 线程3被放入blocking queue
        second_to_third.acquire();
        printThird.run();
    }
}
  • 关于信号量
//pseudo code
struct {
	int counter;//表示目前的资源数量
	queue q;//用于存放等待中的线程
} sem_t 

//v operation: release
signal(sem_t *s) {
	s.counter++;
	//counter小于等于0则说明有线程在排队等待消费资源,所以需要队列中的资源移出,然后唤醒线程	
	if (s.counter <= 0) {
		remove(s.q, p);
		wakeup(q);
	}
}

//p operation: wait
wait(sem_t *s) {
	s.counter--;
	//counter为负说明目前没有资源可供消费,则需要将目前进程放进等待队列, 然后block掉
	if (s.counter < 0) {
		add this thread to s.q;
		block();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值