生產者與消費者問題

TING-KING-TING發表於2020-04-06

在這裡插入圖片描述

public class Student {
	String name;
	int age;
}

public class SetThread implements Runnable{
	private Student s=new Student();
	public SetThread(Student s){
		this.s=s;
	}
	@Override
	public void run() {
		s.name="張三";
		s.age=24;
	}
	
}
public class GetThread implements Runnable{
	private Student s=new Student();
	public GetThread(Student s){
		this.s=s;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(s.name+"---"+s.age);
	}
	
}
public class StudentDemo {
	public static void main(String[] args) {
		//建立資源
		Student s=new Student();
		
		//設定和獲取的類
		SetThread st=new SetThread(s);
		GetThread gt=new GetThread(s);
		
		//執行緒類
		Thread t1=new Thread(st);
		Thread t2=new Thread(gt);
		
		t1.start();
		t2.start();
	}
}

執行緒的安全問題:

A:是否為多執行緒環境
B:是否共享資料
C:是否有多條語句操作共享資料

解決方案:

加鎖
注意:
	A:不同種類的執行緒都要加鎖。
	B:不同種類的執行緒加的鎖必須是同一把。
public class Student {
	String name;
	int age;
}

public class SetThread implements Runnable{
	private Student s=new Student();
	private int x=0;
	public SetThread(Student s){
		this.s=s;
	}
	@Override
	public void run() {
		while(true){
			synchronized (s) {
				if(x%2==0){
					s.name="張三";
					s.age=24;
				}else{
					s.name="李四";
					s.age=34;
				}
				x++;
			}
		}
	}
	
}

public class GetThread implements Runnable {
	private Student s = new Student();

	public GetThread(Student s) {
		this.s = s;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			synchronized (s) {

				System.out.println(s.name + "---" + s.age);
			}
		}
	}

}

/*
 * 分析:
 * 資源類:Student
 * 設定學生資料:SetThread(生產者)
 * 獲取學生資料:GetThread(消費者)
 * 測試類:StudentDemo
 */
public class StudentDemo {
	public static void main(String[] args) {
		//建立資源
		Student s=new Student();
		
		//設定和獲取的類
		SetThread st=new SetThread(s);
		GetThread gt=new GetThread(s);
		
		//執行緒類
		Thread t1=new Thread(st);
		Thread t2=new Thread(gt);
		
		t1.start();
		t2.start();
	}
}

相關文章