package test;
import java.util.concurrent.TimeUnit;
public class A implements Runnable {
private int tickets = 100;
@Override
public void run() {
while (true)
synchronized (this) {
if (tickets > 0) {
if(tickets==80&&Thread.currentThread().getName().equals("AAA")){
throw new RuntimeException();
}
try {
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickets--;
System.out.println(Thread.currentThread().getName() + "卖出一张" + tickets);
} else {
try {
TimeUnit.SECONDS.sleep(1);
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
package test;
public class AverageFinder {
public static void main(String[] args) throws InterruptedException {
A a = new A();
Thread t1 = new Thread(a,"AAA");
Thread t2 = new Thread(a,"BBB");
t1.start();
t2.start();
System.out.println("end...");
}
}