本帖最后由 lwy0319 于 2014-4-3 04:43 编辑
试着根据交通灯系统先写一个路口车辆刷新的小样,但是计数器总是隔两个,求解
- import java.util.*;
- class Road{
- public List<String> road=new ArrayList<String>();
- }
- class Addcar implements Runnable{
- Road r;
- Addcar(Road r){
- this.r=r;
- }
- public void run(){
- for(int i=1;i<100;i++){
- synchronized(r){
- if(r.road.size()==0){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- r.road.add("car"+i);
- System.out.println(r.road.get(0)+"驶入");
- }else{
- try {
- r.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- r.notify();
- }
- }
- }
- }
- class Removecar implements Runnable{
- Road r;
- Removecar(Road r){
- this.r=r;
- }
- public void run() {
- for(int i=1;i<100;i++){
- synchronized(r){
- if(r.road.size()!=0){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(r.road.get(0)+"驶出");
- r.road.remove(r.road.get(0));
- }else{
- try {
- r.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- r.notify();
- }
- }
- }
- }
- public class ThreadDemo1 {
- public static void main(String[] args){
- Road r=new Road();
- Addcar writer=new Addcar(r);
- Removecar reader=new Removecar(r);
- new Thread(writer).start();
- new Thread(reader).start();
- }
- }
复制代码 是因为它每轮都要等待一次,但是这个时候i++了么?如果较真的话有没有办法优化这个问题?虽然如果不计数的话我的目的也算达到一部分了
|