JAVA basics: Notes for JavaThread

Source: Internet
Author: User
JAVA basics: Notes for JavaThread-Linux general technology-Linux programming and kernel information. Java thread programming is very simple. But sometimes you will see some usage errors about the thread. The following are some precautions.

1. synchronization object persistence
All java objects are references.

For local variables and parameters, the basic data types such as int, float, double, and boolean in java are all on the stack. These basic types cannot be synchronized. The objects in java (the root Object is an Object) are all in the heap, and the reference pointing to the Object is on the stack.

The synchronization object in java is actually synchronizing the object address referred to by reference.
Note that do not assign a value to the synchronization object again. For example.
Class A implements Runnable {
Object lock = new Object ();

Void run (){
For (...){
Synchronized (lock ){
// Do something
...
Lock = new Object ();
}
}
}

The synchronization code in the run function is meaningless. Because each lock is assigned a new object's reference, each thread is synchronized with the new reference.
You may find it strange to give an example. Because I have seen such code, the synchronization object is assigned a new value in other functions.
This issue is hard to find out.
Therefore, the synchronization object should be declared as final.
Final Object lock = new Object ();



It is also a good choice to use the Singleton Pattern design mode to obtain synchronization objects.

2. How to place shared data
There are two methods to implement the Thread. One is to inherit the Thread class and the other is to implement the Runnable interface.

In the preceding example, the Runnable interface is implemented. This method is recommended in this article.

First, put the data to be shared in a class that implements the Runnable interface, and then pass the instance of this class to the constructor of multiple threads. In this way, multiple newly created threads share one Runnable instance and share the same data.

If you use the method that inherits the Thread class, you have to use static members. If a large amount of data is shared, a large number of static members are required, making the Program Data Structure messy and difficult to expand. This situation should be avoided as much as possible.

Write a multi-threaded code to handle a slightly complex problem. The advantages and disadvantages of the two methods.

3. Synchronization Granularity
The smaller the thread synchronization granularity, the better. That is, the smaller the code block for thread synchronization, the better. Avoid using synchronized modifiers to declare methods. Try to use synchronized (anObject). If you do not want to introduce a new synchronization object, use synchronized (this. In addition, the smaller the synchronized code block, the better.

4. notifications between threads
Here, we use the word "notification" instead of "communication" to avoid the extended meaning.

Notifications between threads are implemented through the wait (), Y (), or yyall () Methods of Object objects.

Here is an example to illustrate how it works:

Assume there are two threads, A and B. Share a synchronization object, lock.

1. First, thread A obtains the lock synchronization object through synchronized (lock), then calls the lock. wait () function, discards the lock synchronization object, thread A stops running, and enters the waiting queue.

2. thread B acquires the lock synchronization object abandoned by thread A through synchronized (lock), completes some processing, and then calls lock. Y () or lock. notifyAll () notifies thread A in the waiting queue.

3. Thread A comes out of the waiting queue, enters the ready queue, and waits for scheduling.

4. Thread B continues processing. After synchronized (lock) blocks are generated, the lock synchronization object is discarded.

5. Thread A obtains the lock synchronization object and continues running.



The sample code is as follows:

Public class SharedResource implements Runnable {

Object lock = new Object ();



Public void run (){

// Obtain the name of the current thread.

String threadName = Thread. currentThread (). getName ();



If ("A". equals (threadName )){

Synchronized (lock) {// thread A obtains the lock synchronization object through synchronized (lock)

Try {

System. out. println ("A gives up lock .");

Lock. wait (); // call the lock. wait () function to discard the lock synchronization object,

// Thread A stops running and enters the waiting queue.

} Catch (InterruptedException e ){

}



// After thread A obtains the lock synchronization object again, it continues to run.

System. out. println ("A got lock again and continue to run .");

} // End of synchronized (lock)

}



If ("B". equals (threadName )){

Synchronized (lock) {// thread B obtains the lock synchronization object abandoned by thread A through synchronized (lock)

System. out. println ("B got lock .");



Lock. Y (); // notify thread A in the waiting queue to enter the ready queue and wait for scheduling.



// Thread B continues processing. After synchronized (lock) blocks are generated, the lock synchronization object is discarded.

System. out. println ("B gives up lock .");

} // End of synchronized (lock)



Boolean hasLock = Thread. holdsLock (lock); // check whether B has a lock synchronization object.

System. out. println ("B has lock? -- "+ HasLock); // false.

}

}

}



Public class TestMain {

Public static void main (){

Runnable resource = new SharedResource ();



Thread A = new Thread (resource, "");

A. start ();



// Force the main thread to stop running so that thread A can start running.

Try {

Thread. sleep (500 );

} Catch (InterruptedException e ){

}



Thread B = new Thread (resource, "B ");

B. start ();

}

}



5. Cross-class synchronization object
For simple problems, you can put the synchronization code for accessing shared resources in a class.

However, for complex problems, we need to divide the problem into several parts and need several different classes to deal with the problem. In this case, you need to share the synchronization object in different classes. For example, shared synchronization objects are shared between producers and consumers and between readers and writers.

How to share synchronization objects in different classes. There are several methods to achieve this,

(1) The preceding method uses static members (or Singleton Pattern .)

(2) Use the parameter transfer method to pass the synchronization object to different classes.

(3) Use the "atomicity" of string constants ".



For the third method, here is an explanation. Generally, string constants in the program code are unique after compilation. That is, there are no two identical string constants in the memory.

(Normally, C ++ and C programming have the same features after compilation .)

For example, we have the following code.

String A = "atom ";

String B = "atom ";

We have reason to think that A and B point to the same String constant. That is, A = B.

Note that the code for declaring string variables does not comply with the above rules.

String C = new String ("atom ");

String D = new String ("atom ");

Here the C and D declarations are the Declaration of string variables, So C! = D.



With the above understanding, we can use string constants as synchronization objects.

For example, we use synchronized ("myLock") and "myLock" in different classes ". wait (), "myLock ". notify (). This code can synchronize threads between different classes.

This method is not strongly recommended in this article.



This article recommends the second method. (2) use the parameter transfer method to pass the synchronization object to different classes.
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.