/*
5輛汽車過山洞,依次經過山洞。每輛車通過山洞花費10秒,使用多線程實現。
思路:創建5個線程,操作同一個資源,山洞
操作資源的時間爲10秒sleep(10*1000)
某個線程在執行時,其他線程不能操作該資源。同步synchronized(){}
*/
class Bus extends Thread
{
private String name;
private static Object obj = new Object();
public Bus(String name)
{
this.name = name;
}
public String getBusName()
{
return name;
}
public void run()
{
synchronized(obj)
{
System.out.println(Thread.currentThread().getName()+"\t"+this.getBusName()+"正在穿越山洞!!");
try{
Thread.sleep(10*1000);
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"\t"+this.getBusName()+"已經穿過山洞了");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
Bus t1 = new Bus("一號車");
Bus t2 = new Bus("二號車");
Bus t3 = new Bus("三號車");
Bus t4 = new Bus("四號車");
Bus t5 = new Bus("五號車");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
/*
2. 用多線程模擬蜜蜂和熊的關係。
蜜蜂是生產者,熊是消費者。蜜蜂生產蜂蜜是累加的過程,熊吃蜂蜜是批量(滿100吃掉)的過程。
生產者和消費者之間使用通知方式告知對方。注意不能出現死鎖的現象。
思路:創建兩個線程類,蜜蜂類和熊類,創建一個集合累計蜂蜜數,滿100時,通知熊可以吃。
注意:如果蜂蜜數集合中沒有滿100蜂蜜,則熊線程等待,
在熊吃蜜蜂的過程中,蜜蜂等待
cpu自動從鎖池等待隊列中選擇線程執行。
*/
//生產者
import java.util.*;
class Beans extends Thread
{
final static int MAX = 100;
List<Integer> list;
String name;
public Beans(List<Integer> list,String name)
{
this.list = list;
this.name = name;
}
public void run()
{
int i =1;
while(true)
{
synchronized(list)
{
int size = list.size();
if(size<MAX)
{
list.add(new Integer(i));
System.out.println(name+"蜜蜂生產第" + i+"份蜜!!");
i ++ ;
list.notifyAll(); //喚醒屬於當前對象的等待隊列中的所有線程,拿到獲取鎖資格。
}
else //如果蜂蜜數量大於等於100,通知熊可以吃了
{
try
{
list.wait();//使當前線程進入等待隊列中,並釋放鎖,允許其他線程進入同步代碼塊,
}
catch(Exception e){}
}
}
}
}
}
//消費者
class Bear extends Thread
{
List<Integer> list;
String name;
public Bear(List<Integer> list,String name)
{
this.list = list;
this.name = name;
}
public void run()
{
while(true)
{
synchronized(list)
{
int size = list.size();
if(size>=100)
{
for(int i=0;i<size;i++)
{
list.remove(0);
}
System.out.println(name+"吃了100份蜂蜜!!-----------------");
list.notify();//喚醒屬於當前對象的等待隊列中的所有線程,準備獲得鎖。
}
else
{
try
{
list.wait();
}
catch(Exception e){}
}
}
}
}
}
class ThreadDemo2
{
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
Beans t1 = new Beans(list,"lucy");
Beans t2 = new Beans(list,"lili");
Bear t3 = new Bear(list,"熊大");
t1.start();
t2.start();
t3.start();
}
}