Multi-threaded questions

Source: Internet
Author: User

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

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.