public class MyRunnable implements Runnable { private int site=50; // private int num=0; // public MyRunnable() { } public MyRunnable(int site, int num) { this.site = site; this.num = num; } @Override public void run() { String name=Thread.currentThread().getName(); while (true){ buy(name); if (site==0){ break; } } } public synchronized void buy(String name) { if (site>0){ try { site--; num++; Thread.sleep(600); System.out.println(name+"抢到了第"+num+"张票,剩余"+site+"张票"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public static void main(String[] args) { MyRunnable y = new MyRunnable(); Thread t = new Thread(y,"票贩子A"); Thread t2 = new Thread(y,"票贩子B"); Thread t3 = new Thread(y,"票贩子S"); t2.start(); t.start(); t3.start(); }
public class MyRunnable2 implements Runnable{ private int site=50; // private int num=0; @Override public void run() { String name=Thread.currentThread().getName(); while (true){ synchronized (this){ try { if (site>0) { Thread.sleep(200); site--; num++; System.out.println(name+"抢到了第"+num+"张票,剩余"+site+"张票"); } } catch (InterruptedException e) { e.printStackTrace(); } } if (site==0){ break; } } } }
MyRunnable2 myRunnable2 = new MyRunnable2(); Thread t = new Thread(myRunnable2,"票贩子A"); Thread t2 = new Thread(myRunnable2,"票贩子3"); Thread t3 = new Thread(myRunnable2,"票贩子d"); Thread t4 = new Thread(myRunnable2,"票贩子s"); t4.start(); t.start();t3.start();t2.start();