package cn.itcast.thread;
/*
* 创建新线程第二种方式,实现接口方式
* 对售票案例,进行改进
* 延迟处理,出现错误的票数
* 同步技术,保证线程安全性,同步代码块
*
* 速度降低,数据安全
*/
class RunnableTicket implements Runnable {
private int tickets = 100;
private Object obj = new Object();
public void run() {
while (true) {
synchronized(obj){
if (tickets > 0) {
try{Thread.sleep(10);}catch(Exception ex){}
System.out.println(Thread.currentThread().getName() + " 出售第"+ tickets--);
}
}
}
}
}
public class ThreadDemo8 {
public static void main(String[] args) {
RunnableTicket r = new RunnableTicket();
Thread t0 = new Thread(r);
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t0.start();
t1.start();
t2.start();
}
}
|
|