Thread synchronization Initial Solution---reproduced

Source: Internet
Author: User
Tags ticket

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.