Java第十次作业--多线程
(一)学习总结
1.用思维导图对java多线程的学习内容进行总结。
2.下面是一个单线程实现的龟兔赛跑游戏。
class Tortoise implements Runnable {
int tortoiseStep;
public Tortoise(int tortoiseStep) {
this.tortoiseStep = tortoiseStep;
}
public void run() {
for (int i = 1; i < 11; i++) {
System.out.println("乌龟跑了" + i + "步...");
}
}
};
class Hare implements Runnable {
int hareStep;
public Hare(int hareStep) {
this.hareStep = hareStep;
}
public void run() {
System.out.println("龟兔赛跑开始了...");
for (int i = 1; i < 11; i++) {
System.out.println("兔子跑了" + i + "步...");
}
}
};
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();
}
}
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;
super.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;
super.notify();
return this.product;
}
}
(二)实验总结
-
实验内容:
-
1.模拟三个老师同时分发80分作业,每个老师相当于一个线程。
程序设计思路:
1.建立Take类实现Runnable接口;
2.使用synchronized关键字将一个方法声明成同步方法;
3.建立Test方法,创建对象,启动线程
-
2.模拟一个银行存款的程序。假设有两个储户都去银行往同一个账户进行存款,一次存100,每人存三次。要求储户每存一次钱,账户余额增加100,并在控制台输出当前账户的余额。
程序设计思路:
1.建立银行类,定义一个存储账户余额的变量以及一个存款的方法
2.建立储户类,实现向账户存款3次。每一个储户是一个线程
3.建立测试类,创建客户对象,启动线程