初识并发问题
初识并发问题
//多个线程同时操作同一个对象
//买火车票的例子
//可能存在的问题:多个线程操作同一个资源的情况下,线程不安全,数据可能紊乱
public class TestThread4 implements Runnable {
private int ticketNUms=10;
@Override
public void run() {
while (true){
if(ticketNUms<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNUms--+"张票");
}
}
public static void main(String[] args) {
TestThread4 testThread4=new TestThread4();
new Thread(testThread4,"学生").start();
new Thread(testThread4,"老师").start();
new Thread(testThread4,"可恶的黄牛党").start();
}
}
模拟龟兔赛跑
/模拟龟兔赛跑模拟类
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("兔子")){
try {
Thread.sleep(1>>4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag=gameOver(i);
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
//判断比赛是否结束
public 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;
}
return false;
}
}
import com.multithreading.entity.Race;
public class TestThread5 {
public static void main(String[] args) {
Race race=new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
}
Callable
好处:1.可以定义返回值。 2.可以抛出异常。


浙公网安备 33010602011771号