The thread safety problem is caused by the fact that the thread is blocking when executing multiple statements, and then another thread is started without executing it. //Workaround is to synchronize the code block: Synchronized (object)//synchronized (object)//{// code that needs to be synchronized//}class Ticket implements Runnable{private int ticket = +; Object obj = new Object (); public void Run () {while (true) {Synchronized (obj)
//Note Here the premise of using synchronization is two threads or more, and you must ensure that multiple threads use a "lock".
//Also be careful not to put the run () method all in synchronized, as this is a single thread. Some code does not need to put in the synchronized, only need to put in the {if (ticket>0) {Try{thread.sleep (10);} catch (Exception e) {}//here try to block sleep, you will find a negative "ticket",//This means that the thread value inside the memory is used publicly
(because the interface class creates one, it shares the data), so here we need thread synchronization with thread-safety issues synchronizedSystem.out.println (Thread.CurrentThread (). GetName () + "current Ticket" +ticket--); }}}}}
class Threadsecure{public static void Main (string[] args) {Ticket t = new Ticket (); thread T1 = new Thread (t); thread t2 = new Thread (t); thread t3 = new Thread (t); thread t4 = new thread (t); T1.start (); T2.start (); T3.start (); T4.start (); }}
Thread synchronization Initial Solution---reproduced