标签:current 线程 print star new over interrupt bool err
//多线程同时操作同一个对象
//抢火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据会出现紊乱 (并发问题)
public class ThreadTest04 implements Runnable{
//票数
private int ticketNums = 20 ;
@Override
public void run() {
while (true){
if (ticketNums < 1){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"第"+ticketNums+"票");
ticketNums--;
}
}
public static void main(String[] args) {
ThreadTest04 threadTest04 = new ThreadTest04();
new Thread(threadTest04,"线程1").start();
new Thread(threadTest04,"线程2").start();
new Thread(threadTest04,"线程3").start();
}
}
发现问题:多个线程操作同一个资源的情况下,线程不安全,数据会出现紊乱 (并发问题)
//模拟龟兔赛跑
public class ThreadTest05 implements Runnable {
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子睡觉
if (Thread.currentThread().getName() == "兔子" && i%10 == 0){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"第"+i+"步");
}
}
//判断是否完成比赛
private boolean gameOver(int step){
//判断是否有胜利者
if(winner!=null){//已经有了胜利者了
return true;
}else if (step == 100){
winner = Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}else {
return false;
}
}
public static void main(String[] args) {
ThreadTest05 threadTest05 = new ThreadTest05();
new Thread(threadTest05,"兔子").start();
new Thread(threadTest05,"乌龟").start();
}
}
标签:current 线程 print star new over interrupt bool err
原文地址:https://www.cnblogs.com/saxonsong/p/14680117.html