Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the security of threads

Shulou Source: shulou.com Published: 2022-06-03 06:34:10 10月03日 Update

This article introduces the relevant knowledge of "what is the safety of threads?" in the operation of actual cases, many people will encounter such a dilemma, and then 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!

Step 1: stateless classes

Here we write a simple thread-safe class. How simple is it? As shown below

Public class SafeDemo {public int sum (int n, int m) {return n + m;}}

It's that simple. We say this class is thread-safe.

Why is it safe?

Because this class has no state, that is, a stateless class

Only the local variable NJM, which exists in the stack, is unique to each thread, and the heap is shared only if it is not shared with other threads.

Therefore, when each thread operates sum, the corresponding NMagne m is only visible to itself, so of course it is safe.

Well, through the example above, we know what a thread-safe class is, so that's the end of this section. Goodbye.

In the above example, we give a stateless class, and then let's add a state to try.

Step 2: add a state variable

Add a state variable (static attribute) with the following code

Public class UnSafeDemo {static int a = 0; public static void main (String [] args) throws InterruptedException {/ / Thread 1 new Thread (())-> {for (int jung0 for j {for (int job0) J {for (int junio j {for (int jung0 witch j {for (int jung0 witch j)

Tags: Thread variable state atom security method code that is run two example local condition variable synchronization output content multiple subclass case Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Linux MySQL Redmi Docker