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

Example Analysis of Java Thread Safety and synchronization

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

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "Java thread safety and synchronization case analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Thread safety issues

Multiple threads may share (access) the same resource

For example, accessing the same object, the same variable, the same file

When multiple threads access the same resource, it is easy to cause data confusion and data security problems, which is called thread safety problem.

Under what circumstances will thread safety problems occur?

Multiple threads share the same resource

And at least one thread is performing the write operation

Example: saving money and withdrawing money

There are two threads: saving and withdrawing.

Save money and withdraw money

Thread 1 balance thread 2

1000 "- 1000

1000 "1000 -" 2000

1000 "- 500"

Correct: the balance at the end should be 1500, not 500,

The problem of buying tickets

There are 2 threads to sell tickets.

Sell tickets

Thread 1 votes Thread 2

1000 "- 1000

1000-1-"999

999 "- 1000-1

Correct: the balance at the end should be 998, not 999

Ticket purchase error (non-thread synchronization) instance:

Public class love implements Runnable {private int piao=3000;// has 3000 tickets public boolean sale () {/ / ture represents there are still tickets; false reps have no tickets if (piao1;} public void run () {while (sale ()); / / cycle execution; until the tickets are sold out and return false} public class Main {public static void main (String [] a) {love tjlove = new love (); for (int item1tI)

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