黑马程序员技术交流社区
标题:
多线程模拟火车站卖票。
[打印本页]
作者:
刘文秀
时间:
2016-7-26 23:19
标题:
多线程模拟火车站卖票。
package com.itheima02;
public class Demo01_Ticket {
public static void main(String[] args) {
Demo02_Runnable dr = new Demo02_Runnable();
Thread th = new Thread(dr);
Thread th1 = new Thread(dr);
Thread th2 = new Thread(dr);
th.start();
th1.start();
th2.start();
}
}
package com.itheima02;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02_Runnable implements Runnable {
static int tickets = 100;
Lock lock = new ReentrantLock();
private Object obj = new Object();
@Override
public void run() {
while(true) {
synchronized (obj) {
//lock.lock();
if(tickets > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
String s = Thread.currentThread().getName();
System.out.println(s + "正在售:第"+tickets--+"张票");
}else {
break;
}
}
//lock.unlock();
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2