Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Java Thread Safety and synchronization

Shulou Source: shulou.com Published: 2022-05-31 22:37:19 10月23日 Update

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)

Tags: Thread synchronization problem security object method statement instance ticket selling multiple technology analysis balance function withdrawal data result resource output case analysis Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Technology Redmi macOS Microsoft