再谈java中的多线程问题

162 阅读2分钟

我在初学多线程的时候,首先是感觉没用,其次是感觉难,就是简单的了解一下,知道了多线程的两种实现方式,一种是继承Thread类,重写run方法,另一种是实现Runnable接口,重写run方法,当时还写了一篇博客,算是入门吧,翻过来看看感觉写的还是挺全面的,这里给出那篇博客的链接blog.csdn.net/HeZhiYing_/…

今天再在该基础上探讨一个新的问题,关于等待的问题

我先说一下问题,就例如我们用现金买东西,我们排成了一队,如果一个人在买东西,该物品价值95元,他给了售货员100元钱,然而售货员没有5元的钱,所以二者就会处于僵持的状态,我们想要的是,先让下一个人去购物,是不是他会有零钱呢,这里就用到了wait等待,其中wait是等待,notifyAll是唤醒所有的等待notify是唤醒一个等待

这里是用户1先执行,在他后面还有5元的,可以换零钱,所以他等待一会就可以了


public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable,"用户1");
        Thread thread1 = new Thread(myRunnable,"用户2");

        thread.start();
        thread1.start();
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        if(Thread.currentThread().getName().equals("用户1")) {
            shopping(100);
        } else {
            try {
                Thread.sleep(1000); //这里睡眠1秒的意思是让用户1先执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            shopping(5);
        }
    }

    private synchronized void shopping (int money) {
        if(money == 5) {
            System.out.println(Thread.currentThread().getName() + "钱正好");
        } else {
            try {
                System.out.println(Thread.currentThread().getName() + "等待一会");
                wait();
                System.out.println(Thread.currentThread().getName() + "可以购物了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        notifyAll(); //唤醒wait
    }
}

 这里是先让用户2执行,当用户1需要换零钱的时候,后面已经没有带零钱的人了,就一直等待了(不考虑前面的零钱)


public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable,"用户1");
        Thread thread1 = new Thread(myRunnable,"用户2");

        thread.start();
        thread1.start();
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        if(Thread.currentThread().getName().equals("用户1")) {
            try {
                Thread.sleep(1000); //这里睡眠1秒的意思是让用户1先执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            shopping(100);
        } else {

            shopping(5);
        }
    }

    private synchronized void shopping (int money) {
        if(money == 5) {
            System.out.println(Thread.currentThread().getName() + "钱正好");
        } else {
            try {
                System.out.println(Thread.currentThread().getName() + "等待一会");
                wait();
                System.out.println(Thread.currentThread().getName() + "可以购物了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        notifyAll(); //唤醒wait
    }
}