Java synchronization method of handling security thread Thread class inheritance



/ **
* using a synchronization method of treating inherited security thread in the embodiment of the Thread class
*
* /
class Window4 the extends Thread {


Private static int Ticket = 100;

@Override
public void RUN () {

the while (to true) {

Show ();
}

}
Private the synchronized static void Show () {// synchronization monitor: Window4.class
// the synchronized Private void Show () {// synchronization monitor: t1, t2, t3. Such a solution is wrong
IF (Ticket> 0) {

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

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


public class WindowTest4 {
public static void main(String[] args) {
Window4 t1 = new Window4();
Window4 t2 = new Window4();
Window4 t3 = new Window4();


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

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

}
}

Guess you like

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