class Ticket implements Runnable{
private int count = 5;
@Override
public void run(){
for(int i=1; i<=100; i++){
sale();
}
}
private synchronized void sale(){
if(count >0){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("票有" + count--);
}
}
}
public class T{
public static void main(String[] args){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
本文提供了一个使用Java实现的售票程序示例,通过synchronized关键字确保线程安全。该示例展示了如何创建一个可被多个线程共享的Ticket类,并实现其run方法来模拟售票过程。在Ticket类中定义了一个count变量跟踪剩余票数,并通过synchronized关键字保护的sale方法来实现同步操作。
2142

被折叠的 条评论
为什么被折叠?



