java自學之路-----線程(2)

兩個練習線程的例子:

1.賣票代碼{

/*
有一個資源類,裏面有100張票要賣出,有賣票的方法
*/

class Ticket implements Runnable{
	private int ticket = 1000;
	
	public void run(){
		
		while(true)
			synchronized(this){
				try{
					Thread.sleep(10);
				}catch(Exception e){}			
				if(ticket>0)
					sell();
				else
					return ;
			}			
	}
	public void sell(){
		System.out.println(Thread.currentThread().getName() + "窗口" + "正在出售第" + ticket-- + "張票");
	}
}
//創建三個線程執行買票任務
public class TicketDemo{
	public static void main(String[] args){
		Ticket t = new Ticket();
		
		Thread t0 = new Thread(t);
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		
		t0.start();
		t1.start();
		t2.start();
	}
}


}


2.生產者消費者代碼{

/*
wait():讓線程處於凍結狀態,wait的線程存儲到線程池中
notify():喚醒線程池中任意一個線程
notifyAll():喚醒線程池中所有線程
這三個方法必須定義在同步中,用於操作線程狀態的方法要明確操作那個鎖的線程,線程池是和鎖綁定的,
一個鎖中的notify只能喚醒該鎖中wait的線程
*/
//有一資源類,
class Resource{
	private int num = 0;
	private boolean flag = false;
	//生產的方法
	public void set(){
		if(flag)
			try{wait();}catch(InterruptedException e){}
		else{
			System.out.println("生產第" + (++num) + "個包子");
			flag = true;
			notifyAll();//不用notify是因爲有可能所有線程都凍結,導致死鎖
		}
	}	
	//消費的方法
	public void get(){
		if(!flag)
			try{wait();}catch(InterruptedException e){}
		else{
			System.out.println("正在吃第" + num + "個包子");
			flag = false;
			notifyAll();
		}
	}	
}
//生產者
class Producer implements Runnable{
	Resource r = null;	
	Producer(Resource r){
		this.r = r;
	}
	public void run(){
		while(true){
			synchronized(r){
				r.set();	
			}
		}		
	}
}
//消費者
class Consumer implements Runnable{
	Resource r = null;
	
	Consumer(Resource r){
		this.r = r;
	}	
	public void run(){
		while(true){
			synchronized(r){
				r.get();
			}
		}
	}
}

public class ProducerConsumerDemo{
	public static void main(String[] args){
		//創建資源,生產者,消費者的任務
		Resource r = new Resource();
		Producer p = new Producer(r);
		Consumer c = new Consumer(r);	
		//創建生產者與消費者	
		Thread t0 = new Thread(p);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		Thread t3 = new Thread(c);		
		//執行任務
		t0.start();
		t1.start();
		t2.start();
		t3.start();		
	}
}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章