Java synchronization method of handling security thread implement Runnable



/ **
* Use thread synchronization methods to solve the security problem implement Runnable
*
*
* Summary of the synchronization methods:
* 1. The synchronization method still involves synchronizing the monitor, but we do not need to explicitly declare.
* 2. A non-static method of synchronization is synchronization monitor: the this
* static method of synchronization is synchronization monitor: this class itself
*
* /


class Window3 the implements the Runnable {

Private int Ticket = 100;

@Override
public void RUN () {
the while (to true) {

Show ();
}
}

Private the synchronized void Show () {// synchronization monitor: the this
// the synchronized (the this) {

IF (Ticket> 0) {

the try {
the Thread.sleep (100);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);

ticket--;
}
//}
}
}


public class WindowTest3 {
public static void main(String[] args) {
Window3 w = new Window3();

Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);

t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");

t1.start();
t2.start();
t3.start();
}

}

Guess you like

Origin www.cnblogs.com/wpy188/p/12099890.html