Make a thread safe in Java

xiaoxiao2021-03-20  230

Make a thread safe in Java

Author: Builder.com

Thursday, March 4 2004 12:06 PM

This article is translated from builder.com, please do not reprint without permission

In the Java application, the plurality of threads created are very simple, as long as you create java.lang.thread instances by calling the Start method. But you want multi-threaded applications to get the results you want is not always so easy. Here is some points to remember when you create a synchronization program.

Click Here to Find Out More!

The instance variable is default thread safe. Even if you only consider declaring instance variables, they can also manipulate and view any method of that instance. If the non-synchronized method is called both different threads simultaneously, then the two threads can operate the variables at any time. For example, the following code:

1 Class Account {

2 private int balance;

3

4 public int withdraw (int amount) {

5 if (Balance> = Amount) {

6 balance - = Amount;

7 returnon

8 }

9 else {

10 returnograph;

11}

12}

13}

Assume that there are two threads (T1 and T2), both threads are equally equal to the amount of balance. If T1 calls the Withdraw method and is forced to exit before the actual withdrawal after the balance is checked, T2 will pass the balance check and finally perform the payment action. The account balance is now negative. The easiest way to solve this problem is to synchronize access to the WITHDRAW method.

The instance parameter is default the thread secure. For example, in the following method:

Public void foo (int count) {

...

}

No matter how many threads simultaneously call the Foo method, no confusion will be compliant without any case; when the thread calls this method, each thread uses the method of the method parameters. If a method only manipulates the parameters passed to it, then the method is automatically secure.

Synchronization only needs to synchronize. Some programmers have started synchronizing everything after experiencing some questions related to synchronization or without any synchronous related experience. Be sure to resist this temptation.

The overhead brought by synchronization is very large, even if there is only one thread to access an object. To remember that all code needs to be threads because they may not run in a multi-threaded environment at all. Unscrupulous thread safety (just like immature optimization) rarely produce the results you expect.

Author: David Petersheim is director of Genscape application development company. He designs and develops server-side applications to get and process live energy data.

转载请注明原文地址:https://www.9cbs.com/read-130367.html

New Post(0)