java10

2.下面是一个单线程实现的龟兔赛跑游戏。

添加代码

class Tortoise implements Runnable {
	private int n;
	static int i=0;
	static int q=0;
	public Tortoise(int n) {
		this.n = n;
	}

	public void run() {
		while(i<n){
			q++;
			if(q%2==0){
	
					System.out.println("兔子睡着了zzz");
					
			}
			else{
				i+=2;
				System.out.println("兔子已经跑了"+i+"米了");
			}
		}
	}
}

class Hare implements Runnable {
	private int n;
	static int j=0;
	public Hare(int n) {
		this.n = n;
	}
	public void run() {
		
		while(j<n){
			j++;
			System.out.println("乌龟已经跑了"+j+"米了");
		


		}
	}

}

3.下面的程序是模拟了生产者——消费者问题,生产者生产10个数,消费者依次消费10个数,运行程序,看结果是否正常?存在什么问题?说明原因。使用synchronized, wait, notify解决程序出现的问题。写出修改的部分程序即可。

class Clerk {
        private int product = -1; // -1 表示目前没有产品
        private int p ;
        // 这个方法由生产者呼叫
        public synchronized void setProduct(int product) {
            if (this.product != -1) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.product = product;
            p = this.product;
            System.out.printf("生产者设定 (%d)%n", this.product);
            getProduct();
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.product = -1;
            notify();
        }
            // 这个方法由消费者呼叫
            public synchronized int getProduct() {
                if (this.product == -1) {
                    try {
                        wait();
                    }catch (InterruptedException e) {
                e.printStackTrace();
                    }
                }
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("消费者取走 (%d)%n", p);
            this.product = -1;
            notify();
            return this.product;
        }
     }

(三)代码托管

http://git.oschina.net/shuoge/java10

posted @ 2017-06-03 20:55  朔朔  阅读(186)  评论(0)    收藏  举报