多线程-JUC-问题解决(饿汉式、哲学家就餐、交替输出)

1.饿汉式问题

在这里插入图片描述

2. 哲学家就餐问题——死锁

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;

/**
 * 哲学家就餐问题——死锁
 */
@Slf4j(topic = "c.test")
public class Test {
    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");
        new Philosopher("苏格拉底",1,c1,c2).start();
        new Philosopher("柏拉图",2,c2,c3).start();
        new Philosopher("亚里士多德",3,c3,c4).start();
        new Philosopher("赫拉克利特",4,c4,c5).start();
        new Philosopher("阿基米德",5,c5,c1).start();
    }

}

/**
 * 哲学家类
 */
@Slf4j(topic = "c.Philosopher")
class Philosopher extends Thread{
    private Chopstick left;
    private Chopstick right;
    private int index;
    public Philosopher(String name, int index , Chopstick left, Chopstick right){
        super(name);
        this.index = index;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            // 奇偶分组,奇数先左右,偶数先右手。
            if(index %2 == 0){
                // 尝试获取左手的筷子
                synchronized (left){
                    SleepHelper.sleepSeconds(1 + index);
                    log.debug(left.toString() + "左");
                    // 尝试获取右手的筷子
                    synchronized (right){
                        log.debug(left.toString() + "右");
                        eat();
                    }
                }
            }else {
                // 尝试获取右手的筷子
                synchronized (right){
                    log.debug(left.toString() + "右");
                    // 尝试获取左手的筷子
                    synchronized (left){
                        log.debug(left.toString() + "左");
                        eat();
                    }
                }
            }

        }
    }

    private void eat(){
        log.debug("eating...");
        SleepHelper.sleepSeconds(1);
    }

}



/**
 * 筷子类
 */
class Chopstick{
    String name;
    public Chopstick(String name){
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}

/**
 * 睡眠类
 */
class SleepHelper{

    public static void sleepSeconds(long seconds){
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

3.交替输出

方法一:LockSupport

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.LockSupport;

@Slf4j
public class Test02 {

    static Thread t1 = null, t2 = null;
    public static void main(String[] args) {
        char[] ai = "123456".toCharArray();
        char[] ac = "ABCDEF".toCharArray();

        t1 = new Thread(()->{
            for (char c : ai){
                log.debug("{}",c);
                LockSupport.unpark(t2); // 叫醒t2
                LockSupport.park(); // t1阻塞,当前线程阻塞
            }
        },"t1");

        t2 = new Thread(()->{
            for (char c : ac){
                // 重点!!! 先挂起,上一个 Thread 先叫醒
                LockSupport.park(); // t2阻塞,当前线程阻塞
                log.debug("{}",c);
                LockSupport.unpark(t1); // 叫醒t1
            }
        },"t2");
        t1.start();
        t2.start();
    }
}

方法二:synchronized 、wait 、 notify

import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.concurrent.locks.LockSupport;

/**
 * 交替输出,但是不能确保1先输出还是A先输出
 */
@Slf4j
public class Test03 {

    static Thread t1 = null, t2 = null;
    public static void main(String[] args){
        final Object o = new Object();
        char[] ai = "123456".toCharArray();
        char[] ac = "ABCDEF".toCharArray();

        t1 = new Thread(()->{
            synchronized (o){
                for (char c : ai){
                    log.debug("{}",c);
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        },"t1");

        t2 = new Thread(()->{
            synchronized (o){
                for (char c : ac){
                    o.notify();
                    log.debug("{}",c);
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        },"t2");


        t1.start();
        t2.start();
    }
}

方法三:reentrantLock方式

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 交替输出,reentrantLock方式
 */
@Slf4j
public class Test04 {

    static Thread t1 = null, t2 = null;
    public static void main(String[] args){
        char[] ai = "123456".toCharArray();
        char[] ac = "ABCDEF".toCharArray();

        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();

        // 设置计数器 ,为1
        CountDownLatch latch = new CountDownLatch(1);

        t1 = new Thread(()->{
            try {
                // 调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lock.lock();

            try{
                for (char c : ai){
                    log.debug("{}",c);
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t1");

        t2 = new Thread(()->{
            lock.lock();
            try{
                for (char c : ac){
                    log.debug("{}",c);
                    //将 计数器count值减1
                    latch.countDown();
                    condition1.signal();
                    condition2.await();
                }
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t2");


        t1.start();
        t2.start();
    }
}

交替输入ABC

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 交替输出,ABCABC
 */
@Slf4j
public class Test05 {

    static Thread t1 = null, t2 = null, t3 = null;
    public static void main(String[] args){
        int num = 3;
        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();
        // 设置计数器 ,为1
        CountDownLatch latch1 = new CountDownLatch(1);
        CountDownLatch latch2 = new CountDownLatch(1);

        t1 = new Thread(()->{
            lock.lock();
            try{
                for (int i = 0; i < num; i++) {
                    if(i == 0) latch1.countDown();

                    log.debug("A");
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t1");

        t2 = new Thread(()->{
            try {
                latch1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try{
                for (int i = 0; i < num; i++) {
                    if(i == 0) latch2.countDown();

                    log.debug("B");
                    condition3.signal();
                    condition2.await();
                }
                condition3.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t2");
        t3 = new Thread(()->{
            try {
                latch1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try{
                for (int i = 0; i < num; i++) {
                    if(i == 0) latch2.countDown();

                    log.debug("C");
                    condition1.signal();
                    condition3.await();
                }
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t3");

        t1.start();
        t2.start();
        t3.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值