Java's synchronized block processing thread safety issues of class inheritance Thread

com.atguigu.java Package Penalty for; 

/ **

* /
/ **
* synchronous code block address security thread Thread class way of inheritance
*
* Example: Create three ticket windows, the total number of votes for the 100 using inheritance Thread. class way
*
* Note: the inheritance thread class to create multi-threaded mode, this acts as a synchronization monitors used with caution, given the current class act as synchronization monitors.
*
* /
Class Window2 the extends the Thread {


Private static int Ticket = 100;

Private static Object obj = new new Object ();

@Override
public void RUN () {

the while (to true) {
// correct
// the synchronized (obj) {
the synchronized (Window2.class) {// Class clazz = Window2.class, Window2.class only loaded once
// wrong way: this represents t1, t2, t3 three objects
// synchronized (this) {

if(ticket > 0){

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

System.out.println(getName() + ":卖票,票号为:" + ticket);
ticket--;
}else{
break;
}
}

}

}
}


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


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

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

}
}

Guess you like

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