A simple multi-threaded tickets Demo

Thread Package; 

public class Test02 { 
// define the initial number of votes public static int = 20 is chepiao; public {static void main (String [] args)
     Test02 Test02 new new = T ();
// Create a thread anonymous class Thread t1 = new Thread ( ) { @Override public void RUN () {
              // add synchronization lock the synchronized (Test02.class) {
                    // stop sold IF (chepiao <= 0) { return; } // the TODO Auto-Generated Method Stub the try { T .jianfa (); } the catch (InterruptedException E) { // the TODO Auto-Generated Block the catch e.printStackTrace (); } super.run (); } } };           // start threads 30 for (int I =. 1; I <30; I ++) { new new the Thread (T1) .start (); } } // votes -1 public void the synchronized jianfa () throws InterruptedException { chepiao--; System.out.println ( "threads:". + Thread.currentThread () getName () + ", grab a ticket, the remaining" + chepiao + "! Zhang"); } }
Note: when the variables are shared thread, is preferably used AtomicInteger for incrementing or decrementing

  

Guess you like

Origin www.cnblogs.com/mzxx/p/11351349.html