java多線程之生產者消費者

遇到問題,就要針對解決。多線程之生產者消費者實現。多線程

 

消費者ide

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();

    }

}
相關文章
相關標籤/搜索