1. 程式人生 > >Java多執行緒--同步與死鎖:synchronized;等待與喚醒:wait、notify、notifyAll;生命週期

Java多執行緒--同步與死鎖:synchronized;等待與喚醒:wait、notify、notifyAll;生命週期

class Info{	// 定義資訊類
	private String name = "李興華";	 // 定義name屬性
	private String content = "JAVA講師"  ;		// 定義content屬性
	private boolean flag = false ;	// 設定標誌位
	public synchronized void set(String name,String content){
		if(!flag){
			try{
				super.wait() ;
			}catch(InterruptedException e){
				e.printStackTrace() ;
			}
		}
		this.setName(name) ;	// 設定名稱
		try{
			Thread.sleep(300) ;
		}catch(InterruptedException e){
			e.printStackTrace() ;
		}
		this.setContent(content) ;	// 設定內容
		flag  = false ;	// 改變標誌位,表示可以取走
		super.notify() ;
	}
	public synchronized void get(){
		if(flag){
			try{
				super.wait() ;
			}catch(InterruptedException e){
				e.printStackTrace() ;
			}
		}
		try{
			Thread.sleep(300) ;
		}catch(InterruptedException e){
			e.printStackTrace() ;
		}
		System.out.println(this.getName() + 
			" --> " + this.getContent()) ;
		flag  = true ;	// 改變標誌位,表示可以生產
		super.notify() ;
	}
	public void setName(String name){
		this.name = name ;
	}
	public void setContent(String content){
		this.content = content ;
	}
	public String getName(){
		return this.name ;
	}
	public String getContent(){
		return this.content ;
	}
};
class Producer implements Runnable{	// 通過Runnable實現多執行緒
	private Info info = null ;		// 儲存Info引用
	public Producer(Info info){
		this.info = info ;
	}
	public void run(){
		boolean flag = false ;	// 定義標記位
		for(int i=0;i<50;i++){
			if(flag){
				this.info.set("李興華","JAVA講師") ;	// 設定名稱
				flag = false ;
			}else{
				this.info.set("mldn","www.mldnjava.cn") ;	// 設定名稱
				flag = true ;
			}
		}
	}
};
class Consumer implements Runnable{
	private Info info = null ;
	public Consumer(Info info){
		this.info = info ;
	}
	public void run(){
		for(int i=0;i<50;i++){
			this.info.get() ;
		}
	}
};
public class ThreadCaseDemo03{
	public static void main(String args[]){
		Info info = new Info();	// 例項化Info物件
		Producer pro = new Producer(info) ;	// 生產者
		Consumer con = new Consumer(info) ;	// 消費者
		new Thread(pro).start() ;
		new Thread(con).start() ;
	}
};

6、執行緒的生命週期



class MyThread implements Runnable{
	private boolean flag = true ;	// 定義標誌位
	public void run(){
		int i = 0 ;
		while(this.flag){
			System.out.println(Thread.currentThread().getName()
				+"執行,i = " + (i++)) ;
		}
	}
	public void stop(){
		this.flag = false ;	// 修改標誌位
	}
};
public class StopDemo{
	public static void main(String args[]){
		MyThread my = new MyThread() ;
		Thread t = new Thread(my,"執行緒") ;	// 建立執行緒物件
		t.start() ;	// 啟動執行緒
		try{
			Thread.sleep(30) ;
		}catch(Exception e){
			
		}
		my.stop() ;	// 修改標誌位,停止執行
	}
};