第一题:
class Car extends Thread{
private String name;
private Locked lock;
public Car(String name,Locked lock){
this.name = name;
this.lock = lock;
}
public void run(){
synchronized(lock){
System.out.println("车号:" + name + ",开始进入隧道...");
for(int i=1;i<=10;i++){
try{
System.out.println("进入隧道第" + i + "秒");
Thread.sleep(1000*1);
}catch(Exception e){};
}
System.out.println("车号:"+ name + ",结束进入隧道...");
}
}
}
class Locked{
//空锁...
}
class CarDemo{
public static void main(String[] args){
Locked lock = new Locked();
Car car001 = new Car("car001",lock);
Car car002 = new Car("car002",lock);
Car car003 = new Car("car003",lock);
Car car004 = new Car("car004",lock);
Car car005 = new Car("car005",lock);
car001.start();
car002.start();
car003.start();
car004.start();
car005.start();
}
}
第二题:
import java.util.ArrayList;
import java.util.List;
class Bee extends Thread{
private String name;
private List<Integer> list;
private int i = 1;
public Bee(String name,List<Integer> list){
this.name = name;
this.list = list;
}
public void run(){
while(true){
synchronized(list){
if(list.size() >= 10){
try{
list.wait();
}catch(Exception e){};
}else{
try{
Thread.sleep(1000);
}catch(Exception e){};
System.out.println("蜜蜂号:" + name + ",生产第" + i + "次蜂蜜!");
list.add(new Integer(i));
i ++;
list.notify();
}
}
}
}
}
class Bear extends Thread{
private String name;
private List<Integer> list;
private int total = 1;
private Locked lock;
public Bear(String name,List<Integer> list){
this.name = name;
this.list = list;
}
public void run(){
while(true){
synchronized(list){
if(list.size() >= 10){
System.out.println("熊消费:" + total + "次!");
total ++;
list.removeAll(list);
try{
Thread.sleep(2000);
}catch(Exception e){};
list.notify();
}else{
try{
list.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
class ProductDemo{
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
Bee bee001 = new Bee("001",list);
Bee bee002 = new Bee("002",list);
Bee bee003 = new Bee("003",list);
bee001.start();
bee002.start();
bee003.start();
Bear bear = new Bear("001",list);
bear.start();
}
}
转载于:https://blog.51cto.com/senlinmin/1773149