java基础第八天

/*




1. 5辆汽车过山洞,依次经过山洞。每辆车通过山洞花费10秒,使用多线程实现。


class Shan {


}



class Car extends Thread {


Shan shan;

String name;


public Car(String name, Shan shan) {

this.name = name;

this.shan = shan;

public void run() {

synchronized (shan) {

System.out.println("wo is " + name);

try {

Thread.sleep(2000);

}catch (Exception e){

}

}

}


}


class Demo {


public static void main(String[] arg) {


Shan shan = new Shan();

Car c1 = new Car("1",shan);

Car c2 = new Car("2",shan);

Car c3 = new Car("3",shan);

Car c4 = new Car("4",shan);

Car c5 = new Car("5",shan);

Car c11 = new Car("11",shan);

Car c12 = new Car("12",shan);

Car c13 = new Car("13",shan);

Car c14 = new Car("14",shan);

Car c15 = new Car("15",shan);



c1.start();

c2.start();

c3.start();

c4.start();

c5.start();


c11.start();

c12.start();

c13.start();

c14.start();

c15.start();

}


}



*/




/*






2. 用多线程模拟蜜蜂和熊的关系。

   蜜蜂是生产者,熊是消费者。蜜蜂生产蜂蜜是累加的过程,熊吃蜂蜜是批量(满100吃掉)的过程。

   生产者和消费者之间使用通知方式告知对方。注意不能出现死锁的现象。


class Fengmi {


int nu;


}


class Beam extends Thread{


Fengmi fm;

public Beam (Fengmi fm) {

this.fm = fm;

}

public void run() {

synchronized(fm) {

while(true) {

System.out.println(++fm.nu);

if (fm.nu == 100) {

fm.nu=100;

try {

fm.notify();

fm.wait();

   } catch (Exception e) {

}

}

}

}

}


}



class Bear extends Thread{

Fengmi fm;


public Bear (Fengmi fm){

this.fm = fm;

}


public void run() {

while(true) {

synchronized(fm) {

if (fm.nu == 100) {

fm.nu = 0;

System.out.println("bear 都吃了");

try {

fm.notify();

System.out.println("等待中");

fm.wait();

   } catch (Exception e) {

}


}

}


}


}


}


class Demo {


public static void main(String[] arg) {

Fengmi fm = new Fengmi();

Beam beam = new Beam(fm);

Bear bear = new Bear(fm);



beam.start();

bear.start();


}


}


*/


你可能感兴趣的:(java)