Multi-threaded synchronization and communication

Source: Internet
Author: User
Tags volatile

Multithreading:

One, the method of synchronization

1, synchronized

The most effective way to make rational use of resources and improve efficiency. Bring these advantages at the same time, but also for developers to bring some annoyance, such as inconsistent data, can lead to serious consequences, the current use of the most is through the synchronized to achieve synchronization of data, from the following aspects of the introduction of synchronized:

To solve the problem of multi-threaded concurrency, is through a queue, one, if the method or code block plus synchronized, is equal to acquire the lock, the other thread can only wait for the method or code block is executed after the lock is freed, waiting for the thread to get to the lock, to execute the code inside the code block.

and synchronized inseparable is the lock, lock has class lock and object lock, object lock and Class lock independent, do not interfere with each other, there are several situations

1.1, in the static above the synchronized can get to the class lock, when there is a method to obtain the class lock, the other method of adding a static synchronized must wait for the class lock to be released to get to the class lock, and execute the method inside

private static synchronized void DoA () throws Exception {


Thread.Sleep (1000 * 3);//sleep for 3 seconds

System.out.println ("A sleep Finish");

}

private static synchronized void DoB () {

System.out.println ("B sleep Finish");

}

private static void report (String name) {

SYSTEM.OUT.PRINTLN (name + "Start Sleep");

}

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

New Thread (New Runnable () {

public void Run () {
try {
Report ("A");
DoA ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}). Start ();

New Thread (New Runnable () {

public void Run () {
Report ("B");
DoB ();
}
}). Start ();
}

Results:
A Start sleep
B Start sleep
A Sleep Finish
B Sleep Finish

1.2. To acquire this object lock, the other method or block of code must wait until the object lock is released before acquiring the object lock and executing the subsequent code.

1.3. When acquiring the same object lock, different threads need to wait, but when different objects get different object locks, they do not affect each other.


Final object p1 = new Object ();
Final object P2 = new Object ();

New Thread (New Runnable () {

public void Run () {
Synchronized (p1) {
System.out.println (Thread.CurrentThread (). GetName () + "Get P1 object lock");
try {
Thread.Sleep (1000 * 3);
System.out.println (Thread.CurrentThread (). GetName () + "Release P1 object Lock");
} catch (Exception e) {
E.printstacktrace ();
}
}
}
}). Start ();

New Thread (New Runnable () {

public void Run () {
Synchronized (p1) {
System.out.println (Thread.CurrentThread (). GetName () + "Get P1 object lock");
}
}
}). Start ();

Output:
Thread-0 get P1 Object lock
Thread-0 releasing P1 object lock
Thread-1 get P1 Object lock


When you change the P1 in the following thread to P2, the output is as follows

Thread-0 get P1 Object lock
Thread-1 get P2 Object lock
Thread-0 releasing P1 object lock


2. Atomic variables

Dirty reads: Inconsistent data

Volatile keyword: A new thread will copy a copy into its own memory, and the modified variable that is common to the main thread does not change the value of the variable in the main thread, only the variable is preceded by the volatile keyword, forcing the thread to get or modify the value of the variable in memory in the main thread. The visibility of the variable can be guaranteed, but it is not atomic and unsafe.

Synchronization method

2.1. Add Lock

2.2. Using Atomic variables

Code:


Public volatile static int volatilecount = 0;
public static int synccount = 0;
public static Atomicinteger Autocount = new Atomicinteger (0);
public static Void Inc () {
try {
Thread.Sleep (+);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
volatilecount++;
Syncinc ();
AutoInc ();
}
private static void AutoInc () {
Autocount.incrementandget ();
}
private static synchronized void Syncinc () {
synccount++;
}
public static void Main (string[] args) throws Interruptedexception {
for (int i = 0; i <; i++) {
Thread t = new Thread (new Runnable () {
public void run () {
Volatiletest.inc ();
}
});
T.start ();
}
Thread.Sleep (+);
SYSTEM.OUT.PRINTLN ("Running result: counter.volatilecount=" + volatiletest.volatilecount);
System.out.println ("Run Result: counter.synccount=" + volatiletest.synccount);
System.out.println ("Run Result: counter.autocount=" + volatiletest.autocount);
}
Output:


Running Result: counter.volatilecount=45
Running Result: counter.synccount=50
Running Result: counter.autocount=50

3.ThreadLocal
Threadlocal provides another solution for concurrency, providing a single space for each thread by exchanging space for time
Code:
public class Threadlocaltest {
private static threadlocal<string> ThreadLocal = new threadlocal<string> ();
public static void SetValue (String value) {
Threadlocal.set (value);
}
public static String GetValue () {
return Threadlocal.get ();
}
public static void Main (string[] args) {
New Thread (New Runnable () {
public void Run () {
SetValue ("Fred");
System.out.println ("threadlocal=" + getValue ());
}
}, "T1"). Start ();
New Thread (New Runnable () {
public void Run () {
System.out.println ("threadlocal=" + getValue ());
}
}, "T2"). Start ();
}
}
Results:
Threadlocal=fred
Threadlocal=null



Second, the communication between the threads

Wait/notify

1, must use the Synchronization keyword

2, wait release lock notify does not release the lock, notify will not immediately execute the wait thread code, only notify after the thread execution, will not execute the wait threads code

Code (analog blocking queue):


Public final static linkedlist<string> Quene = new linkedlist<string> ();

Public final Static Object lock = new Object ();

Public final static int quene_size = 5;

Public final static int quene_min = 0;

Public final static Atomicinteger count = new Atomicinteger (0);

public static void Main (string[] arg) {

Final Myqueue Quene = new Myqueue ();
for (int i = 0; i < i++) {
New Thread (New Runnable () {
public void Run () {
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Quene.put (count.getandincrement () + "");
}
}). Start ();

New Thread (New Runnable () {
public void Run () {
Quene.get ();
}
}). Start ();
}

}

public int GetSize () {
return Quene.size ();
}

Public String get () {
Synchronized (lock) {
while (quene_min = = GetSize ()) {
try {
Lock.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
String value = Quene.get (quene_min);
Quene.remove (quene_min);
System.out.println ("Remove" + value);
Lock.notify ();
return value;
}
}

public void put (String value) {
Synchronized (lock) {
while (quene_size = = GetSize ()) {
try {
Lock.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Quene.add (GetSize (), value);
System.out.println ("Add" + value);
Lock.notify ();
}
}

Results:
Added 1
Remove 1
Added 0
Added 2
Added 3
Remove 0
Remove 2
Remove 3
Added 5
Added 6
Added 7
Added 9
Remove 5
Remove 6
Added 8
Remove 7
Remove 9
Remove 8
Added 4
Remove 4

Multi-threaded synchronization and communication

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.