java-Thread Synchronization Issues

Source: Internet
Author: User

1.Timer class

Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classTimerdemo { Public Static voidMain (string[] args)throwsexception{/** Timer class Demo: The Ava.util.Timer class is a timer that allows it to do something on a timed basis, * Method: Schedule (Task,delay,period);//execute task after delay milliseconds and p         The eriod is executed for the cycle cycle. *                * */Timer T=NewTimer ();//T.schedule (New TimerTask ()//        {//@Override//Public void Run () {//System.out.println ("Bombing!!!");//             }//}, +);T.schedule (NewMytimertask (), 3000); //every second, print out the time         while(true) {System.out.println (NewDate (). getseconds ()); Thread.CurrentThread (). Sleep (1000); }      }}//The explosion is achieved every 3 seconds and explodes every 2 seconds, and in this cycle//The reason for writing classes is that we keep using the run code in this class,//This allows you to reuse the run code by using a constant new object.//the reason that int i is written as static is that the object of new is to share data I, so write static//i= (i+1)%count, the result is I with count of the cycle, non-stop cycle. //Note: This cannot be written as an inner class of Timerdemo because a non-static inner class is equivalent to other non-static methods and cannot be//inside declare static variable (static int i)!! or static Method!! classMytimertaskextendsTimerTask {Static intI=0; @Override Public voidrun () {System.out.println ("Bombing!!!"); NewTimer (). Schedule (NewMytimertask (), (i+2) *1000); I= (i+1)%2; }}

2. How multiple Threads access shared objects and data

2.1 If each thread executes the same code, the same Runnable object can be used, and the Runnable object has that shared data, for example, the ticket system can do so.

2.2 If the code executed by each thread is different, it is necessary to use different runnable objects in the following two ways to implement the data sharing between these runnable objects:

A. Encapsulate the shared data in another object, and then pass the object one at a to each Runnable object. Each thread's method of manipulating shared data is also assigned to that object to complete,

This makes it easy to achieve mutual exclusion and communication for each operation that is performed on the data.

B. Use these runnable objects as internal classes in a class, share the data as member variables in the external class, and assign each thread to the external class how to manipulate the shared data in order to implement

These methods of external classes are called by the individual runnable objects of the inner class as mutual exclusion and communication of the various operations performed on the shared data.

The combination of the above two ways: the shared data is encapsulated in another object, each thread to the method of operation of the shared data is also assigned to the object to complete, the object as a member of the external class variables or local variables in the method

The Runnable object for each thread acts as a member inner class or local inner class in an external class.

In short, it is best to synchronize mutually exclusive pieces of code in a few separate methods, these methods are placed in the same class, it is easier to implement the synchronization of mutual exclusion and communication between them.

The extreme and simple way to define a static variable in any class is to be shared by all threads.

3.ThreadLoal Troubleshooting thread synchronization issues (http://blog.csdn.net/qjyong/article/details/2158097)

For the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of " time-changing space ", and ThreadLocal adopts " space-changing time ".

The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread , so it can be accessed at the same time without affecting each other.

Threadlocal is not a thread, but a local variable of thread, and perhaps it is more understandable to name it a thread local variable (threadlocalvariable).

Threadlocal class interface is very simple, there are only 4 methods, let us first look at:

    • void set (Object value)

Sets the value of the thread local variable for the current thread.

    • Public Object Get ()

This method returns the thread local variable that corresponds to the current thread.

    • public void Remove ()

Removes the value of the current thread local variable to reduce memory usage, which is a new method of JDK 5.0. It should be noted that when the thread ends,

Local variables for the supposed thread are automatically garbage collected, so it is not necessary to explicitly call the method to clear the thread's local variables, but it can speed up the memory reclamation.

    • Protected Object InitialValue ()

Returns the initial value of the thread's local variable, which is a protected method, apparently designed for subclasses to overwrite. This method is a deferred call method,

The thread executes only when it calls get () or set (Object) for the 1th time, and executes only 1 times. The default implementation in Threadlocal returns a null directly.

It is worth mentioning that, in JDK5.0, Threadlocal already supports generics, and the class name of the class has become threadlocal<t>.

The API methods are also adjusted accordingly, and the new version of the API method is void set (t value), t get (), and T InitialValue ().

public class SequenceNumber {

① Overwrite by anonymous inner class ThreadLocal of the InitialValue () method, specifying the initial value

private static threadlocal<integer> SeqNum = new threadlocal<integer>() {

Public Integer InitialValue () {

return 0;

}

};

② gets the next sequence value

public int Getnextnum () {

Seqnum.set (Seqnum.get () +1);

return Seqnum.get ();

}

public static void Main (string[] args)

{

SequenceNumber sn = new SequenceNumber ();

③ 3 thread Sharing SN , each generating serial number

testclient T1 = new TestClient (sn);

TestClient t2 = new TestClient (sn);

testclient t3 = new TestClient (sn);

T1.start ();

T2.start ();

T3.start ();

}

private static class TestClient extends Thread

{

Private SequenceNumber SN;

Public testclient (SequenceNumber sn) {

THIS.SN = SN;

}

public void Run ()

{

for (int i = 0; i < 3; i++) {④ 3 sequence values per thread

System.out.println ("thread[" +thread.currentthread (). GetName () +

"] sn[" +Sn.getnextnum ()+ "]");

}

}

}

}

In general, we define the subclass of threadlocal by means of an anonymous inner class, providing the initial variable value, as shown in the example ①. TestClient threads produce a set of serial numbers, and at ③ we generate 3 testclient that share the same SequenceNumber instance. Run the above code and output the following results on the console:

Thread[thread-2] sn[1]

THREAD[THREAD-0] sn[1]

THREAD[THREAD-1] sn[1]

Thread[thread-2] sn[2]

THREAD[THREAD-0] sn[2]

THREAD[THREAD-1] sn[2]

Thread[thread-2] sn[3]

THREAD[THREAD-0] sn[3]

THREAD[THREAD-1] sn[3]

Summary

Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access.
In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency.

java-Thread 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.