天天看點

線程經典 生産者消費者 兩個完全不…

package sell_ticket;

public class ThreadTicket {

   public static void

main(String[] args) {

MyThread m = new MyThread();  

Thread t1 = new Thread(m);

Thread t2 = new Thread(m);

Thread t3 = new Thread(m);

t1.start();

t2.start();

t3.start();

}    

}

class MyThread implements Runnable{

    private int

ticket=100;

    public void

run(){

while(true){

 try {

 Thread.sleep(1000);

 } catch (InterruptedException e) {

 // TODO Auto-generated catch block

 e.printStackTrace();

   }

 //用synchronized包起來,形成同步代碼塊,但後來發現用不用其實一樣

 synchronized(this){

 if(ticket>0){

 System.out.println(Thread.currentThread().getName()+"出售了"+ticket);          

 ticket--;

 }

    }

第二種,采用堆棧的方式:

 class Producer implements Runnable

    private

String producerName = null;

StoreHouse storeHouse = null;

    public

Producer(String producerName, StoreHouse storeHouse) {

this.producerName = producerName;

this.storeHouse = storeHouse;

setProducerName(String producerName) {

String getProducerName() {

return producerName;

produceProduct() {

int i = 0;

while (true) {

i++;

Product pro = new Product(i);

storeHouse.push(pro);

System.out.println(getProducerName() + " 生産了 " + pro);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

return;

run() {

produceProduct();

class Consumer implements Runnable {

String consumerName = null;

Consumer(String consumerName, StoreHouse storeHouse) {

this.consumerName = consumerName;

setConsumerName(String consumerName) {

String getConsumerName() {

return consumerName;

consumerProduct() {

System.out.println(getConsumerName() + " 消費了 " +

storeHouse.pop());

Thread.sleep(5000);

consumerProduct();

class Product {

productId = 0;

Product(int productId) {

this.productId = productId;

    public int

getProductId() {

return productId;

String toString() {

return Integer.toString(productId);

class StoreHouse {

base = 0;

top = 0;

Product[] products = new Product[10];

synchronized void push(Product product) {

while (top == products.length) {

notify();

System.out.println("倉庫已滿,正等待消費...");

wait();

System.out.println("stop push product because other

reasons");

products[top] = product;

top++;

synchronized Product pop() {

Product pro = null;

while (top == base) {

System.out.println("倉庫已空,正等待生産...");

繼續閱讀