Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Thread Safety problems in Java Multithreading

Shulou Source: shulou.com Published: 2022-06-01 10:25:42 09月30日 Update

This article mainly introduces the example analysis of thread safety problems in Java multithreading, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

1. What is thread safety and thread unsafety?

What is thread safety? When multiple threads access a Java object concurrently, no matter how the system schedules these threads and how these threads will operate alternately, the object can show consistent and correct behavior, so the operation on the object is thread-safe.

If the object shows inconsistent and incorrect behavior, then the operation on the object is not thread-safe, and thread safety problems occur.

two。 Why is self-increment not thread-safe?

Thread safety experiment: two threads add and decrease static variables with an initial value of 0, each doing 5000 times. Is the result 0? The specific code is as follows

Public class ThreadDemo {private static int i = 0; public static void main (String [] args) throws InterruptedException {/ / Thread 1 does 5000 self-incrementing operations on variable I Thread T1 = new Thread (()-> {for (int jung0 int j {for (int jacu0tj)

Tags: Threads code resources security problems variables multiple objects static memory atoms situations conditions two instructions articles analysis consistency three data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MariaDB NVidia Apple Linux