1.过山洞
5辆车汽车过山洞,每次只允许一个车通过,每辆汽车通过时间不同 2 6 8 10
提示,汽车是现象
2.银行存钱取票机的问题
50人去银行,从取票机取票号。每个人取的票号是唯一的。
通过同步代码块和同步方法两种方式实现
--------------------------------------------------------------------------------------
第一题
class NineThreadFiveclass{
public static void main(String[] agrs) {
Car c=new Car("宾利",3000);
Car c1=new Car("奔驰",5000);
RedLight w=new RedLight();
c.start();
c1.start();
w.start();
}
}
//定义车辆进程
class Car extends Thread{
private String name;
private int time;
static Object lock = new Object();
public Car (String name ,int time){
this.name =name;
this.time =time;
}
//定义run方法 即进洞即锁住直到出动
public void run(){
synchronized(lock){
System.out.println("ccc" + name+ "进洞了");
try{
Thread.sleep(time);
}
catch(Exception e){
}
System.out.println("ccc" + name + "出洞了");
}
}
}
//定义守护线程,即在洞里就守护
class RedLight extends Thread{
public RedLight(){
this.setDaemon(true);
}
public void run(){
while (true){
System.out.println("在洞里");
try{
Thread.sleep(1000);
}
catch(Exception e){
}
}
}
}
---------------------------------------------------------------
第二题
class NineThreadBank{
public static void main(String[] agrs) {
Bank pool = new Bank();
Custer c = new Custer("MARRY", pool);
Custer c1 = new Custer("LILI", pool);
c.start();
c1.start();
}
}
class Bank {
private int tickets=50;
public synchronized int Getticks(){
//票号
int tick =tickets;
//票数
tickets --;
return tickets;
}
}
class Custer extends Thread{
private String name ;
private Bank pool;
public Custer (String name, Bank pool ){
this.name=name;
this.pool=pool;
}
public void run(){
while(true){
int no =pool.Getticks();
if(no>0){
System.out.println(name+":"+no);
}
else{
return;
}
}
}
}
--------------------------------------------------------------------------------------
老师的讲解
第一题 :同步方法
class CarCaveDemo{
public static void main(String[] args){
Cave cave =new Cave();
Car c1 =new Car(cave,"马车","8000");
Car c2 =new Car(cave,"电动车","5000");
Car c3 =new Car(cave,"电动车","5000");
c1.start();
c2.start();
c3.start();
}
}
//山洞类
class Cave{
//同步方法 synchronized 汽车通过的方法
public synchronized void crossCar(Car car){
try{
System.out.println(car.name+":开始国山洞");
Thread.sleep(car.time)
System.out.println(car.name+":出山洞了");
}
catch(Exception e){
}
}
}
//汽车类
class Car extends Thread{
//把山洞传过来,定义变量接受它
public Cave cave;
public int time;
public String name;
public Car(Cave cave, String name,int time){
this.cave=cave;
this.time=time;
this.name=name;
}
public void run(){
//this把自己传过来
cave.crossCar(this);
}
}
第二题:取票机
-------------------------------------------------------------------