In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "example analysis of thread safety problems in java". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "example analysis of thread safety problems in java".
1. When will there be security problems with data in a multi-threaded and concurrent environment?
Three conditions:
Condition 1: multithreading concurrency.
Condition 2: there is shared data.
Condition 3: the shared data has the behavior of modification.
After the above three conditions are met, there will be thread safety problems.
Second, how to solve the thread safety problem?
Threads are queued for execution. (cannot be concurrent). Solve thread safety problems with queued execution. This mechanism is called: thread synchronization mechanism.
Third, the case of withdrawal / deposit by the bank
Account class
Package ThreadSafa; / * Bank account * / public class Account {/ / account private String actno; / / balance private double balance; public Account () {} public Account (String actno, double balance) {this.actno = actno; this.balance = balance;} public String getActno () {return actno;} public void setActno (String actno) {this.actno = actno } public double getBalance () {return balance;} public void setBalance (double balance) {this.balance = balance;} / / withdrawal method public void withdraw (double money) {/ / balance before withdrawal double before = this.getBalance (); / / balance after withdrawal double after = before-money / / Update balance try {/ / simulated network delay update balance 100% problems Thread.sleep (1 * 1000);} catch (InterruptedException e) {e.printStackTrace ();} this.setBalance (after);}}
AccountThread class
Package ThreadSafa; public class AccountThread extends Thread {/ / two threads must share the same account object. Private Account act; / / pass the account object public AccountThread (Account act) {this.act = act;} @ Override public void run () {double money = 5000; / / withdrawal act.withdraw (5000) through the constructor System.out.println (Thread.currentThread (). GetName () + "account" + act.getActno () + "withdrawal successful, balance" + act.getBalance ());}}
Test class
Package ThreadSafa; public class Test {public static void main (String [] args) {/ / create account object Account act = new Account ("act-001", 10000); / / create two threads Thread T1 = new AccountThread (act); Thread T2 = new AccountThread (act); / / set name t1.setName ("T1"); t2.setName ("T2") / / start thread t1.start (); t2.start ();}}
Operation problem
Workaround modifying the withdraw method in the Account class
Package ThreadSafa; / * Bank account * / public class Account {/ / account private String actno; / / balance private double balance; public Account () {} public Account (String actno, double balance) {this.actno = actno; this.balance = balance;} public String getActno () {return actno;} public void setActno (String actno) {this.actno = actno } public double getBalance () {return balance;} public void setBalance (double balance) {this.balance = balance } / / withdrawal method public void withdraw (double money) {/ / the following lines of code must be queued by threads, not concurrently / / after a thread has finished executing all the code here Another thread can come in / * the syntax of the thread synchronization mechanism is: the "data" in parentheses after synchronized () {/ / thread synchronization code block} synchronized is quite critical. This data must be shared by multiple threads. What is written in the multithreaded queue ()? That depends on which threads you want to synchronize. Suppose T1, T2, T3, T4, T5, there are five threads, you only want T1 T2 T3 to queue, T4 T5 does not need to queue. What shall I do? You must write a T1 / T2 / T3 shared object in (). This object is not shared for T4 / T5. The sharing object here is: account object account object is shared, so this is the account object! It doesn't have to be this, as long as it's the object shared by multiple threads. * / synchronized (this) {/ / balance before withdrawal double before = this.getBalance (); / / balance after withdrawal double after = before-money / / Update balance try {/ / simulated network delay update balance 100% will cause problems Thread.sleep (1 * 1000);} catch (InterruptedException e) {e.printStackTrace ();} this.setBalance (after) Why is there a thread safety problem?
Computer system resources are allocated in units of processes, where multiple threads are allowed to execute concurrently in the same process, and multiple threads share process-wide resources, such as memory addresses. Thread safety problems may occur when multiple threads access the same memory address concurrently and the value saved by the memory address is variable, so a memory data sharing mechanism is needed to ensure thread safety.
Corresponding to the java service, the shared memory address in the virtual is java's heap memory, such as thread safety issues in the following programs:
Public class ThreadUnsafeDemo {private static final ExecutorService EXECUTOR_SERVICE; static {EXECUTOR_SERVICE = new ThreadPoolExecutor (100,100,100,100 * 10, TimeUnit.SECONDS, new LinkedBlockingQueue (1000), new ThreadFactory () {private AtomicLong atomicLong = new AtomicLong (1); @ Override public Thread newThread (Runnable r) {return newThread (r, "Thread-Safe-Thread-" + atomicLong.getAndIncrement ()) }});} public static void main (String [] args) throws Exception {Map params = new HashMap (); List futureList = new ArrayList (100); for (int I = 0; I < 100; iTunes +) {futureList.add (new CacheOpTask (params) } for (Future future: futureList) {System.out.println ("Future result:" + future.get ());} System.out.println (params);} private static class CacheOpTask implements Callable {private Map params; CacheOpTask (Map params) {this.params = params } @ Override public Integer call () {for (int I = 0; I < 100; iTunes +) {int count = params.getOrDefault ("count", 0); params.put ("count", + + count);} return params.get ("count");}
Create 100 task, and each task accumulates 100 of the elements in the map. The result of the program execution is:
{count=9846}
The expected correct results are:
{count=10000}
As for the causes of this problem, we will analyze it in detail below.
One of the principles for determining thread safety is:
Whether there are multiple threads to access variable shared variables
Thank you for your reading, the above is the content of "example analysis of thread safety problems in java". After the study of this article, I believe you have a deeper understanding of the example analysis of thread safety problems in java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.