小渣飞、 2020-11-12 22:16 采纳率: 87.9%
浏览 16

Java 多线程卡死,是两个线程锁对象不是同一个的原因吗?

public class Clerk {

    public static int productCount = 0;

    public static void main(String[] args) {
        Thread p1 = new Thread(new Producer(new Clerk()));
        p1.setName("生产者一号");
        Thread c1 = new Thread(new Customer(new Clerk()));
        c1.setName("消费者一号");

        p1.start();
        c1.start();

    }
}

/*
    生产者
 */
class Producer implements Runnable {
    private Clerk clerk;
    int count = Clerk.productCount;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public synchronized void run() {
        while (true) {
            if (count < 20) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                System.out.println(Thread.currentThread().getName() + ":生产了第" + count + "个商品");
                notify();
            } else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

/*
    消费者
 */
class Customer implements Runnable {

    private Clerk clerk;
    int count = Clerk.productCount;

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public synchronized void run() {
        while (true) {

            if (count > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                System.out.println(Thread.currentThread().getName() + ":购买了第" + count + "个商品");
                notify();
            } else {
                System.out.println("货已售空,等待商家生产");
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

 

  • 写回答

2条回答 默认 最新

  • 起名字好烦啊 2020-11-13 11:54
    关注

    synchronized锁加在Clerk上好了,在主线程里创建一个clerk,传到两个线程里

    评论

报告相同问题?