这世上有三样东西是别人抢不走的:一是吃进胃里的食物,二是藏在心中的梦想,三是读进大脑的书。

《Java技术》第十次作业计科1501赵健宇-多线程

(一)学习总结

1.用思维导图对java多线程的学习内容进行总结。

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

public class TortoiseHareRace {
    public static void main(String[] args) {
        int totalStep = 10;
        int tortoiseStep = 0;
        int hareStep = 0;
        boolean[] flags = {true,false};
        System.out.println("龟兔赛跑开始了...");
        while(tortoiseStep < totalStep && hareStep < totalStep){
            tortoiseStep++;
            System.out.println("乌龟跑了"+tortoiseStep+"步...");
            boolean isHareSleep = flags[((int)(Math.random()*10))%2];
            if(isHareSleep){
                System.out.println("兔子睡着了zzzz");
            }else{
                hareStep += 2;
                System.out.println("兔子跑了"+hareStep+"步...");
            }
        }       
    }
}

采用Runnable接口的方式用多线程实现这个小游戏。下面给出主线程类,补充Tortoise线程类和Hare线程类。

public class TortoiseHareRace {
	public static void main(String[] args) {
		Tortoise tortoise = new Tortoise(10);
		Hare hare = new Hare(10);
		Thread tortoiseThread = new Thread(tortoise);
		Thread hareThread = new Thread(hare);
		tortoiseThread.start();
		hareThread.start();
	}
}

class Tortoise implements Runnable {
	private int total;
	private int mytotal = 0;
	private boolean game =true;
	public Tortoise(int total) {
		this.total = total;
	}

	public void run() {
		while (game) {
			if (mytotal < total) {
				try {
					Thread.sleep(1000);
					int step = (int)(Math.random()*5+1);
					mytotal+=step;
					System.out.println("小乌龟走了"+mytotal+"步了");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("小乌龟到达终点");
				game=false;
			}
		}
	}
}

class Hare implements Runnable {//tuzi
	private int total;
	private int mytotal = 0;
	private boolean game =true;
	public Hare(int total) {
		this.total = total;
	}

	public void run() {
		while (game) {
			if (mytotal < total) {
				try {
					Thread.sleep(1000);
					int step = (int)(Math.random()*5+1);
					int flag = (int)(Math.random()*2+1);
					if(flag==1){//兔子睡觉了
						System.out.println("小兔子睡觉啦");
					}else{
						mytotal+=step;
						System.out.println("小兔子走了"+mytotal+"步了");
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("兔子到达终点");
				game=false;
			}
		}
	}
}

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

应改为:

class Consumer implements Runnable {
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("消费者开始消耗整数......");
        // 消耗10个整数
        for (int i = 1; i <= 10; i++) {
            try {
                // 等待随机时间
                Thread.sleep((int) (Math.random() * 3000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable {
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("生产者开始生产整数......");
        // 生产1到10的整数
        for (int product = 1; product <= 10; product++) {
            try {
                Thread.sleep((int) Math.random() * 3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.setProduct(product); // 将产品交给店员
        }
    }
}

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

    // 这个方法由消费者呼叫
    public synchronized int getProduct() {
        if (this.product == -1) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("消费者取走 (%d)%n", p);
        this.product = -1;
        super.notify();
        return this.product;
    }
}

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread consumerThread = new Thread(new Consumer(clerk));
        Thread producerThread = new Thread(new Producer(clerk));
        consumerThread.start();
        producerThread.start();
    }
}

4.其他需要总结的内容。

  • int flag = (int)(Math.random()*2+1);生成1-2的随机数

  • java基本数据类型byte,short,int,long,float,double,char,boolean。String不是基本类型。

  • float a =1.1;错 应为float a =1.1f;
    在后面加上f表示该数字是float型的,如果不写的默认的是double型。同理,加上l表示long型

  • 进程和线程的区别:进程是一个程序的执行,线程是进程中独立的执行序列,一个进程可以包含很多线程,线程有时被称为轻量级进程。

(二)实验总结

实验内容:
1.模拟三个老师同时分发80分作业,每个老师相当于一个线程。
程序设计思路:创建三个线程,使用同步方法创建MyThread类

    MyThread mt = new MyThread();
	Thread t1 = new Thread(mt);
	Thread t2 = new Thread(mt);
	Thread t3 = new Thread(mt);
	t1.setName("张老师");
	t2.setName("李老师");
	t3.setName("赵老师");

2.模拟一个银行存款的程序。假设有两个储户都去银行往同一个账户进行存款,一次存100,每人存三次。要求储户每存一次钱,账户余额增加100,并在控制台输出当前账户的余额。
程序设计思路:创建银行类储存钱,使用同步创建账户线程
线程代码:

public class Depositor implements Runnable{
	Bank bk = new Bank();
	public void run() {
		for(int i= 0;i<3;i++){
			save();
		}
	}
	private synchronized void save(){
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		bk.setMoney(100);
		System.out.println(Thread.currentThread().getName()+"存了100元      * 余额"+bk.getMoney());
	}
}

(三)代码托管

点击此处进入码云

posted @ 2017-05-30 10:00  进击的小白V  阅读(321)  评论(0编辑  收藏  举报
感谢观看。转载复制请注明源处~!