一、案例
package com.massimo.thread;
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread04 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums <= 0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "张票");
}
}
public static void main(String[] args) {
TestThread04 ticket = new TestThread04();
new Thread(ticket , "张三").start();
new Thread(ticket , "李四").start();
new Thread(ticket , "黄牛党").start();
}
}
效果:
二、龟兔赛跑
package com.massimo.thread;
//模拟龟兔赛跑
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
//如果比赛结束了,就终止程序
if (flag){
break;
}
System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "米");
}
}
//判断是否完成比赛
public boolean gameOver(int miter){
//判断是否有胜利者
if (winner != null){
return true;
}else {
if (miter >= 100){
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race , "兔子").start();
new Thread(race , "乌龟").start();
}
}