本章通过多个Java多线程实例对多线程进行学习
1. 模拟窗口售票问题
1. 代码
package test;
public class TestSaleTickets {
public static void main(String[] args) {
Counter counter = new Counter();
new Thread(counter, "柜台A").start();
new Thread(counter, "柜台B").start();
new Thread(counter, "柜台C").start();
}
}
/**
* 柜台售票
*/
class Counter implements Runnable{
//总票数
public static int tickets = 20;
@Override
public void run() {
while (tickets > 0){
synchronized (this){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "张票");
}else {
System.out.println(Thread.currentThread().getName() + "票卖完了");
}
try {
Thread.sleep(1000);
tickets--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}