package lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Train implements Runnable {
Train1 t = new Train1();
Lock lock=new ReentrantLock();
@Override
public void run() {
lock.lock();
try{
while (true) {
//当数量大于0的时候,调用方法卖票
if (t.count > 0) {
t.number();
} else {
return;
}
try {
//线程睡200毫秒
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}finally{
lock.unlock();
}
}
}
class Train1 {
int count = 50;
//一张张卖
public int number() {
count -= 1;
System.out.println(Thread.currentThread().getName() + "卖了1张,还剩" + count + "张");
return count;
}
}
package lock;
public class TestTrain {
public static void main(String[] args) {
Runnable r=new Train();
Thread t1=new Thread(r,"1");
Thread t2=new Thread(r,"2");
Thread t3=new Thread(r,"3");
Thread t4=new Thread(r,"4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}