Java synchronized block processing implementation of Runnable thread safety issues



/ **
* Example: Create three ticket windows, the total number of votes for the 100 ways that implement the Runnable interface.
*
* 1. Problem: the process of selling tickets, there has been heavy vote, wrong vote -> emerged thread security
reasons * 2. the problem: when a thread process of ticket operations, upon completion, other threads involved, also operates a ticket yet operational.
* 3. How to fix: When a thread a ticket at the time of the operation, other threads can not get involved. When a thread until the operation is complete ticket, other
* threads before it can begin operation ticket. This occurred even thread a blocked and can not be changed.
*
*
* 4. In Java, we passed synchronization mechanism to address security issues thread.
*
* A way: the synchronization code blocks
*
* the synchronized (sync monitor) {
* // need to be synchronized code
*
*}
* Description: 1. Operation code sharing data, the code that is to be synchronized. -> can not contain code for more, and can not contain less code.
* 2. Shared data: Variable multiple threads co-operation. For example: ticket is the sharing of data.
* 3. Synchronize monitor, commonly known as: lock. Any object of a class, can act as a lock.
* Requirements: multiple threads must share the same lock.
*
* Added: In the way to achieve Runnable interface to create multiple threads, we can consider this act as synchronization monitors.
* Second way: synchronization method.
* If the code to share data in a full declaration operating method, we might as well declare this method synchronized.
*
*
* 5. synchronization, address security issues thread. --- Benefits
* operation synchronization code, to participate in only one thread, other threads wait. The equivalent of a single-threaded process is inefficient. Limitations ---
*
* /
class the Window1 the implements the Runnable {

Private int Ticket = 100;
// Object obj = new new Object ();
// new new Dog Dog Dog = ();
@Override
public void RUN () {
// Object = new new Object obj ();
the while (to true) {
the synchronized (the this) {// this case this: only two ways @ Window1 object: the synchronized (Dog) {

IF (Ticket> 0) {

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

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


ticket--;
} else {
break;
}
}
}
}
}


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

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();
}

}


class Dog{

}

Guess you like

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