本帖最后由 陈振兴 于 2012-9-23 10:10 编辑
问题描述:以此题为例,车库里面很多车位,同时又有很多车辆进出,怎么才能实现并发?
//存车位的停开车的次序输出问题;
class Car{
private String name;
private static int count =200;
private boolean flag = false;
public synchronized void save(String name){
while(flag){
if(count>0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this.name=name+count--;
System.out.println(Thread.currentThread().getName()+"...车主存放...."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void take(){
while(!flag){
if(count>0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"......取车号..."+this.name);
flag=false;
this.notifyAll();
}
}
class CarOwner implements Runnable{
private Car c;
CarOwner(Car c){
this.c=c;
}
public void run(){
while(true){
c.save("+车位号");
}
}
}
class Manna implements Runnable{
private Car c;
Manna(Car c){
this.c=c;
}
public void run(){
while(true){
c.take();
}
}
}
主函数调用:
public static void main(String[] args){
//怎么才能实现并发?
Thread t1 = new Thread(new CarOwner(c));
Thread t4 = new Thread(new CarOwner(c));
Thread t2 = new Thread(new Manna(c));
Thread t3 = new Thread(new Manna(c));
t1.start();
try {
Thread.sleep(5000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t4.start();
t2.start();
try {
Thread.sleep(10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t3.start();
}
2.进程的调度是OS负责的,有的系统为独占式,有的为共享式?有点晕了(这不会指的是OS的cup性能吧)?
3.根据重要性进程 有优先级,多线才程的并发一般不是程序员决定,而是容器决定,这又是怎么理解?(是不是上面得程序就已经写死还是?)
|