Java Multithreading--synchronization issues

Source: Internet
Author: User
Tags instance method

Multi-threaded synchronization relies on the object lock mechanism, the SYNCHRONIZED keyword is behind the use of blocking to achieve mutual access to shared resources.

The following is a simple example of comparative analysis. The work of the instance is very simple, that is, to create 10 threads, each of which prints 100 numbers from 0 to 99, we want the threads to print in sequential order without cross-ordering printing.

First look at the first code, here we add the Synchronized keyword in the run () method, we want to be able to mutually exclusive access to the Run method, but the result is not as we would like it, because here synchronized lock is the This object, that is, the current running thread object itself. 10 threads are created in the code, and each thread holds an object lock on this object, which does not enable thread synchronization.

Class MyThread implements Java.lang.Runnable

{

private int threadId;

public MyThread (int id)

{

This.threadid = ID;

}

Public synchronized Void Run ()

{

for (int i = 0; i <; ++i)

{

System.out.println ("Thread ID:" + This.threadid + ":" + i);

}

}

}

public class Threaddemo

{

public static void Main (string[] args) throws Interruptedexception

{

for (int i = 0; i <; ++i)

{

New Thread (New MyThread (i)). Start ();

Thread.Sleep (1);

}

}

}

As you can tell from the code snippet above, to implement thread synchronization, these threads must compete for a unique shared object lock.

Based on this idea, we will modify the first code as shown below, create a competing object object between threads before creating a startup thread, and then pass a reference to the object object to the lock member variable of each thread object. As a result, the lock members of each thread point to the same object object. In the Run method, we use the synchronzied block for the lock object for local blocking, which allows the thread to compete for this unique shared object lock for synchronization.

Class MyThread implements Java.lang.Runnable

{

private int threadId;

private Object lock;

public MyThread (int id, Object obj)

{

This.threadid = ID;

this.lock = obj;

}

Publicvoid Run ()

{

synchronized (lock)

{

for (int i = 0; i <; ++i)

{

System.out.println ("Thread ID:" + This.threadid + ":" + i);

}

}

}

}

public class Threaddemo

{

public static void Main (string[] args) throws Interruptedexception

{

Object obj = new Object ();

for (int i = 0; i <; ++i)

{

New Thread (New MyThread (i, obj)). Start ();

Thread.Sleep (1);

}

}

}

The second code shows that the key to synchronization is that multiple thread objects compete for the same shared resource, and the code above is implemented externally by creating shared resources and then passing them to the thread. We can also use class member variables to be shared by instances of all classes , so lock can be implemented with a static member object , as shown in the following code:

Class MyThread implements Java.lang.Runnable

{

private int threadId;

Private Static Object lock = new Object ();

public MyThread (int id)

{

This.threadid = ID;

}

Publicvoid Run ()

{

Synchronized (lock)

{

for (int i = 0; i <; ++i)

{

System.out.println ("Thread ID:" + This.threadid + ":" + i);

}

}

}

}

public class Threaddemo

{

public static void Main (string[] args) throws Interruptedexception

{

for (int i = 0; i <; ++i)

{

New Thread (New MyThread (i)). Start ();

Thread.Sleep (1);

}

}

}

Then look at the first code, the instance method is added sychronized keyword blocking is the This object itself, and in the static method to add the Sychronized keyword block is the class itself. static methods are shared by all class instance objects, so thread objects are mutually exclusive access to this static method , allowing for thread synchronization, as shown in the following code:

Class MyThread implements Java.lang.Runnable

{

private int threadId;

public MyThread (int id)

{

This.threadid = ID;

}

Publicvoid Run ()

{

Taskhandler (This.threadid);

}

private static synchronized void taskhandler (int threadId)

{

for (int i = 0; i <; ++i)

{

System.out.println ("Thread ID:" + threadId + ":" + i);

}

}

}

public class Threaddemo

{

public static void Main (string[] args) throws Interruptedexception

{

for (int i = 0; i <; ++i)

{

New Thread (New MyThread (i)). Start ();

Thread.Sleep (1);

}

}

}

Java Thread Synchronization Summary:

1, the purpose of thread synchronization is to protect multiple threads to ask a resource when the destruction of resources. 2, thread synchronization method is implemented by lock, each object has and only one lock, this lock is associated with a specific object, once the thread acquires an object lock, other threads that access the object can no longer access the object's other non-synchronous methods. 3, for the static synchronization method, the lock is for this class, the lock object is the class object. Static and non-static methods of locking do not interfere. A thread acquires the lock, which is obtained when a synchronization method on another object is accessed in a synchronous method. 4, for synchronization, to be awake at all times on which object synchronization, this is the key. 5, write thread-safe classes, you need to pay attention to multiple threads competing access to the logic and security of the resources to make the right judgment, the "atomic" operation to make an analysis, and ensure that other threads during atomic operation can not access the competing resources. 6. When multiple threads wait for an object lock, the thread that does not acquire the lock will block. 7, deadlock is between the threads waiting for lock-lock caused by, in practice, the probability of occurring is very small. Really let you write a deadlock program, not necessarily good, hehe. However, once the program has a deadlock, the program will die.

Java Multithreading--synchronization issues

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.