Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What problems should Java Thread pay attention to?

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces what problems Java Thread should pay attention to, the content is very detailed, interested friends can refer to, hope to be helpful to you.

(wang hailong)

XML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" / >

Thread programming for Java is very simple. But sometimes you see some misuses about threads. Here are some problems that should be paid attention to.

1. The constancy of synchronous objects

All java objects are references.

For local variables and parameters, int, float, double, boolean and other basic data types in java are all on the stack. These basic types cannot be synchronized; the objects in the java (the root object is 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.

The important thing to note is that you should never reassign the synchronization object. For instance.

Class An implements Runnable {

Object lock = new Object ()

Void run () {

For (...) {

Synchronized (lock) {

/ / do something

...

Lock = new Object ()

}

}

}

This synchronization code in the run function is actually meaningless. Because each time the lock is reassigned to the reference of the new object, each thread synchronizes with the new reference.

You may wonder how such an example could be given. Because I have seen such code, synchronization objects are re-assigned new values in other functions.

Such problems are difficult to find out.

Therefore, you should generally declare the synchronization object as final.

Final Object lock = new Object ()

It is also a good choice to use the Singleton Pattern design pattern to get synchronization objects.

2. How to place shared data

There are two ways to implement threads, one is to inherit the Thread class, and the other is to implement the Runnable interface.

The example above uses the method of implementing the Runnable interface. This method is recommended in this paper.

First, put the data that needs to be shared in a class that implements the Runnable interface, and then pass an instance of this class to multiple Thread constructors. In this way, multiple newly created Thread share a single Runnable instance and share the same data.

If you take the method of inheriting the Thread class, you have to use static static members. If a large amount of data is shared, a large number of static static members are needed, which makes the data structure of the program confused and difficult to expand. This situation should be avoided as far as possible.

Write a piece of multithreaded code to deal with a slightly more complicated problem. The pros and cons of the two methods can be easily known at a try.

3. Granularity of synchronization

The smaller the granularity of thread synchronization, the better, that is, the smaller the code block of thread synchronization, the better. Try to avoid declaring methods with synchronized modifiers. Try to use synchronized (anObject), and if you don't want to introduce new synchronization objects, use synchronized (this). Also, the smaller the synchronized code block, the better.

4. Notification between threads

The word "notification" is used here instead of the word "communication" to avoid the expansion of the meaning of the word.

Notification between threads is achieved through the wait () and notify () or notifyAll () methods of the Object object.

Here is an example to illustrate how it works:

Suppose you have two threads, An and B. Share a synchronization object, lock.

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

2. Thread B obtains the lock synchronization object abandoned by thread A through synchronized (lock), finishes some processing, and then calls lock.notify () or lock.notifyAll () to notify thread An 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 the synchronized (lock) block is out, the lock synchronization object is discarded.

5. Thread A gets the lock synchronization object and continues to run.

The example code is as follows:

Public class SharedResource implements Runnable {

Object lock = new Object ()

Public void run () {

/ / gets the name of the current thread.

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

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

Synchronized (lock) {/ / Thread An 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) {

}

/ / Thread A continues to run after it has regained the lock synchronization object.

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.notify (); / / notify thread An in the waiting queue to enter the ready queue and wait for scheduling.

/ / Thread B continues processing, discarding the lock synchronization object after the synchronized (lock) block is out.

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")

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. Synchronization objects across classes

For simple problems, you can put all the synchronization code that accesses the shared resources in one class.

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

How to share synchronization objects in different classes. There are several ways to implement

(1) the method mentioned earlier, using static static members, (or using Singleton Pattern.)

(2) pass synchronization objects to different classes by the method of parameter passing.

(3) make use of the atomicity of string constants.

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

(in general, the same feature is found in the compiled C language programs.) )

For example, we have the following code.

String A = "atom"

String B = "atom"

We have reason to think that An and B point to the same string constant. That is, Avalanche B.

Note that the code that declares string variables does not conform to the above rules.

String C = new String ("atom")

String D = new String ("atom")

The declarations of C and D here are the declarations of string variables, so C! = D.

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

For example, we can synchronize threads between different classes by using code like synchronized ("myLock"), "myLock". Wait (), "myLock". Synchronization ().

The editor does not strongly recommend this usage, but only shows that there is such a method.

The second method is recommended. (2) pass synchronization objects to different classes by passing parameters.

About Java Thread should pay attention to which problems should be shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report