Thread1类
package com.maipiao2;
public class Thread1 extends Thread {
static int target = 0;
@Override
public void run() {
// TODO Auto-generated method stub
while (target < 100) {
synchronized (Object.class) {
//加一个if语句,保证在票数卖到100张以后,等待着的线程不会继续执行target++代码。
if (target < 100) {
target++;
System.out.println(Thread.currentThread().getName() + "卖出了" + target + "张票");
}
else {
System.out.println("卖完了");
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Test类
package com.maipiao2;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread1().start();
new Thread1().start();
new Thread1().start();
new Thread1().start();
new Thread1().start();
new Thread1().start();
new Thread1().start();
new Thread1().start();
}
}