标签:tor image 模拟 name read ret strong 胜利 pack
1.继承Thread类重写run方法
2.继承Runnable接口重写run方法(通常用这种,java单继承的局限性,后期还想继承其他类会无从下手)
package 多线程;
public class BuyTicket {
public static void main(String[] args) {
TickThread tt = new TickThread();
Thread t1 = new Thread(tt,"张三");
Thread t2 = new Thread(tt,"李四");
Thread t3 = new Thread(tt,"王五");
t1.start();
t2.start();
t3.start();
}
}
class TickThread implements Runnable{
private int total = 10;
@Override
public void run() {
while (total>=1) {
total--;
System.out.println(Thread.currentThread().getName() + "买了票,剩余" + total + "张");
}
System.out.println(Thread.currentThread().getName()+"发现售罄");
}
}
由于资源没有加锁,导致数据异常问题
package 多线程;
public class RunGame {
public static void main(String[] args) {
Runner rn = new Runner();
Thread rabbit = new Thread(rn,"rabbit");
Thread tortoise = new Thread(rn,"tortoise");
rabbit.start();
tortoise.start();
}
}
class Runner implements Runnable{
private int stage = 100;
private String winner=null;
@Override
public void run() {
for(int i=1;i<=100;i++){
if(isOver(i)==true) {
Thread.currentThread().interrupt();
break;
}
}
}
boolean isOver(int step){
if (winner!=null){
return true;
}else{
if(step==100){
System.out.println(Thread.currentThread().getName()+"胜利!");
winner=Thread.currentThread().getName();
return true;
}else{
System.out.println(Thread.currentThread().getName()+"->"+step);
return false;
}
}
}
}
标签:tor image 模拟 name read ret strong 胜利 pack
原文地址:https://www.cnblogs.com/shuzi0806/p/12317137.html