java多线程之生产者消费者

遇到问题,就要针对解决。多线程之生产者消费者实现。

消费者

public class Consumer implements Runnable {

    private Account account;

    public Consumer(Account accoun) {

        this.account = accoun;

        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {

        while (true) {

            synchronized (account) {
                if (account.getAmount() >= 1) {

                    int balance = account.getAmount();
                    balance--;
                    account.setAmount(balance);
                    System.out.println(Thread.currentThread().getId() + "扣钱,"
                            + "余额: " + balance);
                    account.notify();
                } else {
                    try {
                        System.out.println(Thread.currentThread().getId()
                                + "钱不够: " + account.getAmount());
                        account.wait();

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }

        }

    }

}



生产者

public class Producer implements Runnable {
    private Account account;

    public Producer(Account accoun) {

        this.account = accoun;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {

        while (true) {

            synchronized (account) {
                if (account.getAmount() <= 5000000) {

                    int balance = account.getAmount();
                    balance++;
                    account.setAmount(balance);
                    System.out.println(Thread.currentThread().getId() + "加钱,"
                            + "余额: " + balance);
                    account.notify();
                } else {
                    try {
                        System.out.println(Thread.currentThread().getId()
                                + "钱满了: " + account.getAmount());
                        account.wait();

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }

        }

    }

}
测试类
public class TestConPro {

    public static void main(String[] args) {

        Account account = new Account();

        Producer pro = new Producer(account);
        Consumer con = new Consumer(account);

        Thread tpro = new Thread(pro);

        Thread tcon = new Thread(con);

        tpro.start();

        tcon.start();

    }

}


 
原创博文,未经许可不得转载,转载请注明出处。
原文地址:https://www.cnblogs.com/Think-007/p/7777878.html