Black Horse Programmer------The summary of multithreading in Java (II.)

Source: Internet
Author: User

Java training, Android training, iOS training,. NET training, looking forward to your communication

In Java Multi-threading, data exceptions can occur if multiple threads are concurrently manipulating shared data

As in the following code:

/* * Mock Sell ticket */class Ticket implements runnable{    private  int tick = ten;    Object obj = new Object ();    public void Run ()    {        while (true)        {                        if (tick>0)            {                try{thread.sleep (10);} catch (Exception e) {}                System.out.println (Thread.CurrentThread (). GetName () + ".... Sale:" + tick--);}        }    }}class  ticketdemo2{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 ();    }}

The result of this code operation:

thread-2....sale:10thread-0....sale:9thread-1....sale:8thread-3....sale:7thread-2....sale:6thread-0....sale:5t Hread-1....sale:4thread-3....sale:3thread-2....sale:2thread-0....sale:1thread-3....sale:0thread-2....sale: -1Th Read-1....sale:-2

Through the results can be seen, the number of votes has a negative, this is a data anomaly, that is, the program appeared in the "Dirty data."

This "dirty data" is caused by the simultaneous operation of shared data at the same time, if you want to avoid "dirty data", you have to ensure that when one thread operations to share data, other threads can not manipulate the shared data.

To solve this problem, you can use the Synchronied keyword to achieve synchronization.

Add the SYNCHRONIZD keyword to the code that needs to be synchronized:

public void Run ()    {while        (true)        {                //here plus synchronized keyword            synchronized (obj) {                if (tick>0)                {                    try{thread.sleep (10);} catch (Exception e) {}                    System.out.println (Thread.CurrentThread (). GetName () + ".... Sale:" + tick--);}}    }

Code blocks modified by the Synchronized keyword are called synchronous code blocks.

It can also be modified by the following code:

Public synchronized void Run () {     

As you can see from the code above, you can synchronize the Run method with the Synchronized keyword between void and public, that is, for an object instance of the same Java class, the Run method can only be called by one thread, and after the current run executes, To be called by other threads. Even if the current thread executes the yield method in the Run method, it just pauses. Because another thread cannot execute the Run method, it will eventually continue to be executed by the current thread.

It can also be used to modify static methods:

Class Test {public    static synchronized void method () {   

We are familiar with the singleton design mode lazy loading method is thread insecure, the code is as follows:

Thread unsafe Singleton Mode class singleton{    private static Singleton sample;    Private Singleton ()    {    } public    static Singleton getinstance ()    {        if (sample = = null)        {            Thread.yield (); In order to magnify Singleton mode of thread insecurity            sample = new Singleton ();        }        return sample;    }} public class Singletontest extends thread{public    void Run ()    {        Singleton Singleton = Singleton.getinstance ();        System.out.println (Singleton.hashcode ());    }    public static void Main (string[] args)    {        Thread threads[] = new THREAD[5];        for (int i = 0; i < threads.length; i++)            threads[i] = new Singletontest ();        for (int i = 0; i < threads.length; i++)            Threads[i].start ();    

The running results of the program are as follows:

17945158271167165921144200254917013819261442002549

The above results may have all the same in different operating environments, but generally the output of these five lines will not be identical. From this output, it can be seen that the object instance obtained by the GetInstance method is five, not the one we expect.

This is because when a thread executes the Thread.yield (), it gives the CPU resources to another thread. Because the statements that created the Singleton object instance are not executed when the thread is switched between threads, these are the if judgments, so there is a case for creating five object instances (four or three object instances may be created. This depends on how many threads have passed the if judgment before the singleton object is created, and may result in a different run each time. To make the above single-piece mode thread-safe, just add the Synchronized keyword to the getinstance. The code is as follows:

public static synchronized Singleton getinstance () {   }

There are, of course, simpler ways to create singleton objects when defining singleton variables, known as "full-han", with the following code:

It is important to understand that regardless of whether the keyword is decorated with non-static methods or static methods, it is not the methods that are locked, but the objects or classes in which the methods reside.

Use the Synchronized keyword to be aware of the scope of the SYNCHRONIZED keyword:

1, is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, As long as a thread accesses one of the synchronized methods, the other thread cannot access any of the synchronized methods in the object at the same time. At this point, the synchronized method of the different object instances is not interfering. In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;

2, is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class.

2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access. The usage is: synchronized (this) {/* block */}, which is scoped to the current object;

3, synchronized keyword is not inherited, that is, the method of the base class synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method.

Black Horse Programmer------The summary of multithreading in Java (II.)

Related Article

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.