package com.kai.lesson1;
//多个线程同时操作同一个对象
//买火车票
//问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 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) {
TestThread4 ticket= new TestThread4();
new Thread(ticket,"A").start();
new Thread(ticket,"B").start();
new Thread(ticket,"C").start();
}
}
例子:
龟兔赛跑
package com.kai.lesson1;
//模拟龟兔赛跑
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(0,2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
Boolean flag=gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
//判断是否完成比赛
private boolean gameOver(int steps){
//判断是否有胜利者
if (winner!=null){
return true;
}else{
if(steps>=100){
winner=Thread.currentThread().getName();
System.out.println("winner is"+ winner);
return true;
}else {
return false;
}
}
}
public static void main(String[] args) {
Race race=new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
}