卖东西
题目要求:
3个平台卖1000件商品,把他们卖东西的过程模拟出来
分析:
需要注意的是线程安全问题,加一个synchronized ,但是这个synchronized 加在哪里呢?注意是不能加在run()方法的前面的,因为他们每个都有自己的run方法,如果加在run方法的前面,就会一直显示的是一个商家去卖东西,我们要把synchronized加在buy()方法的前面
结论:
将synchronized
关键字放在run()
方法前面是不正确的。这是因为synchronized
是用来控制对共享资源的访问的,而run()
方法是线程的执行体,不涉及对共享资源的访问,因此在该方法上加锁并没有意义。
代码:
public class Large {
public static void main(String[] args) {
Sale sale = new Sale();
new Thread(sale,"平台1").start();
new Thread(sale,"平台2").start();
new Thread(sale,"平台3").start();
}
}
class Sale implements Runnable {
private int nums = 1000;
boolean flag = true;
@Override
public void run() {
while(flag) {
buy();
}
}
public void stop() {
flag = false;
}
public synchronized void buy() {
if(nums <= 0) {
stop();
return;
}
//解决线程安全问题
System.out.println(Thread.currentThread().getName() + "销售了第: " + (1000 - --nums) + "件商品");
}
}
龟兔赛跑:
题目要求,去模拟乌龟和兔子进行比赛跑步,当兔子跑到600米的时候需要休息
分析:
这个速度的模拟可以让sleep去模拟,这个是案例也是对sleep的复习
代码:
public class TheTortoiseAndTheHare {
public static void main(String[] args) {
Race race = new Race();//他们两个共用一个赛道
new Thread(race, "兔子").start();
new Thread(race, "乌龟").start();
}
}
class Race implements Runnable {
private static String winner;
@Override
public void run() {
for(int i = 0; !gameOver(i); ) {
if(Thread.currentThread().getName().equals("兔子")) {//兔子
if(i == 600) {//兔子跑到600米 需要休息
try {
Thread.sleep(1200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
i += 12;//间接的模拟速度
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} else {//乌龟
i += 10;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
boolean flag = gameOver(i);
// System.out.println("flag = " + flag);
if(flag) {
break;
}
System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "米");
}
}
private boolean gameOver(int steps) {
if(winner != null) {
return true;
}
if(steps >= 1000) {
winner = Thread.currentThread().getName();
System.out.println("胜利者是: " + winner);
return true;
}
return false;
}
}