Java小白一个,刚开始学习线程,在这个过程中遇到了一些麻烦,经过2天的努力,终于弄懂了用多线程实现卖票的程序,嗯嗯,记录一下!
public class TicketImpDemo {
public static void main(String[] args) {
Runnable target = new ticket();
new Thread(target, "A").start();
new Thread(target, "B").start();
new Thread(target, "C").start();
}
}
class ticket implements Runnable {
static Object o = new Object();
int num = 5000;
@Override
public void run() {
while (num > 0) {
synchronized (o) {
if (num > 0) {
num--;
System.out.println(Thread.currentThread().getName() + "卖出了第" + (5000 - num) + "张票");
}
}
}
System.out.println("票都卖完啦!!!");
}
}
以上便是我的代码,希望能够帮助到大家,同时也欢迎大家批评指正。