Thread safety issues occur because multiple threads are manipulating the shared data.
Solve the idea;
is to encapsulate the thread code that has multiple operations sharing data, and when the thread is executing the code, the other threads are not allowed to participate in the operation. It is necessary for the other threads to participate in the operation when the code is executed by the front-end thread.
Synchronized (object)
{
Code that needs to be synchronized;
}
1, multiple windows at the same time to sell tickets, to ensure that the number of votes not <=0
public class MyThread {public static void main (string[] args) throws Interruptedexception {Ticket Ticket = new MyThread ( ). New Ticket ();//sharing data and operations sharing data is best placed in a class, so the lock is convenient for (int i = 0; i < 4; i++) {//Open 4 windows and sell ticket new Thread (Ticket). Start ();} Class Ticket implements runnable//extends thread{private int num = 1000;//operation shared data Object obj = new object ();//Only new once to protect The uniqueness of the card lock public void run () {while (true) {if (num>0) {synchronized (obj) {if (num>0) {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "..... sale ..." +num--);}}}}}
2.
Multi-threaded questions