a- package ticket.demo;
- public class SellDemo2 {
- public static void main(String[] args) {
- MyRunnable m = new MyRunnable(new TicketShared());
- for (int i = 0; i < 3; i++) {
- new Thread(m).start();
- }
- }
- }
- class MyRunnable implements Runnable {
- private TicketShared t;
- public MyRunnable(TicketShared t) {
- super();
- this.t = t;
- }
- @Override
- public void run() {
- while(true){
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- t.dec();
- }
- }
- }
- class TicketShared {
- private int t = 100;
- public synchronized void dec() {
- if (t > 0) {
- t--;
- System.out.println(Thread.currentThread().getName() + "...售出一张,剩余"
- + t);
- } else {
- System.out.println("票售完了~~");
- System.exit(0);
- }
- }
- }
复制代码
|
|