- public class Exercise5Thread {
- static int tacket = 100;
- public static void main(String[] args) throws Exception {
-
- // Thread t1 = new Thread(){
- // @Override
- // public void run() {
- // this.setName("b");
- // System.out.println(Thread.currentThread().getName());
- // }
- // };
- // t1.start();
-
- // System.out.println(Thread.currentThread().getName());
-
- // Thread.sleep(1000);
-
- // t1.setDaemon(true);
- Sell s = new Sell();
- Thread t1 = new Thread(s);
- t1.setName("1号售票窗口");
- Thread t2 = new Thread(s);
- t2.setName("2号售票窗口");
- Thread t3 = new Thread(s);
- t3.setName("3号售票窗口");
- Thread t4 = new Thread(s);
- t4.setName("4号售票窗口");
-
- t1.start();
- t2.start();
- t3.start();
- t4.start();
-
- }
- }
- class Sell implements Runnable{
- int ticket = 100;
- @Override
- public void run() {
- while(true){
- synchronized(Sell.class){
- if(ticket<=0){
- break;
- }
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"出售第"+(ticket--)+"票");
- }
- }
- }
- }
复制代码 |
|