In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you the "sample analysis of Java thread-safe state", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of Java thread-safe state".
First, observe all states of the thread
The state of the thread is an enumerated type Thread.State
Public static void main (String [] args) {for (Thread.State state: Thread.State.values ()) {System.out.println (state);}}
NEW: I've arranged the work, but I haven't started yet.
RUNNABLE: workable. It can be divided into working and about to start work. Ready state
BLOCKED: these all mean waiting in line for something else.
WAITING: these all mean waiting in line for something else.
TIMED_WAITING: these all mean waiting in line for something else.
TERMINATED: the work is done.
Second, the significance of thread state and state transfer
There is a NEW:Thread object, but PCB does not have it.
RUNNABLE: a thread is executing on CPU or is about to execute on CPU (PCB is in the ready queue and may be scheduled at any time)
The WAITING:wait method results in
The TIMED_WAITING:sleep method results in
BLOCKED: waiting for a lock to cause
TERMINATED: the object is still there, but the PCB is gone
Public static void main (String [] args) {Thread t = new Thread () {@ Override public void run () {for (int I = 0; I < 10000; iTunes +) {}; System.out.println ("before thread starts:" + t.getState ()); t.start () While (t.isAlive ()) {System.out.println ("thread running:" + t.getState ());} System.out.println ("after thread ends:" + t.getState ());}
Third, the risks brought by multithreading
Reasons for thread unsafety
① threads are preemptively executed
The root of all evils of thread unsafety, the scheduling between threads is entirely the responsibility of the kernel, which can not be perceived or controlled in the user code. Between threads, who executes first, who executes later, and who executes where and comes down from the CPU, such a process that users can neither control nor perceive.
The ② auto-increment operation is not atomic
Each + + can be divided into three steps.
Read the data in memory into CPU
Add the data in CPU + 1
Write the calculated data back to memory
If two threads execute sequentially, the result of the calculation is 2.
If two threads execute in parallel, when thread 1 is halfway through the + + operation, the thread also performs the + + operation, which increments twice, but the result is 1.
You must ensure that thread 1save ends and thread 2 load again, so that the calculation result is correct
③ multiple threads try to modify the same variable
If a thread modifies a variable, it is thread safe
Thread safe if multiple threads read the same variable
If multiple threads modify different variables. Thread safety
④ memory visibility causes thread safety problems
⑤ instruction reordering
When compiling the code, the compiler of Java will optimize the instructions and adjust the order of the instructions to ensure that the original logic remains unchanged, so as to improve the efficiency of the program.
Fourth, solve the problem of thread safety
Lock-synchronized
Unlocked
Static class Counter {public int count = 0; public void increase () {count++;}} public static void main (String [] args) throws InterruptedException {Counter counter = new Counter (); Thread T1 = new Thread () {@ Override public void run () {for (int I = 0; I < 50000) ITunes +) {counter.increase ();}; Thread T2 = new Thread () {@ Override public void run () {for (int I = 0; I < 50000; iTunes +) {counter.increase () }; t1.start (); t2.start (); t1.join (); t2.join (); System.out.println (counter.count);}
Locked
Static class Counter {public int count = 0; synchronized public void increase () {count++;}} public static void main (String [] args) throws InterruptedException {Counter counter = new Counter (); Thread T1 = new Thread () {@ Override public void run () {for (int I = 0; I < 50000) ITunes +) {counter.increase ();}; Thread T2 = new Thread () {@ Override public void run () {for (int I = 0; I < 50000; iTunes +) {counter.increase () }; t1.start (); t2.start (); t1.join (); t2.join (); System.out.println (counter.count);}
The synchronized here is used to lock the object counter. Inside the increase method, the locked state is set to false after the ture,increase method exits. If a thread has set the locked state to ture, other threads here try to lock, and it will block.
The characteristic of synchronized-- refresh memory
The working process of synchronized:
1. Acquire mutex
two。 Copy the latest copy of the variable from main memory to working memory
3. Execute the code
4. Refresh the value of the changed shared variable to the main memory
5. Release mutex
The characteristic of synchronized-Mutual exclusion
Public static void main (String [] args) {Object locker = new Object (); Thread T1 = new Thread () {@ Override public void run () {Scanner scanner = new Scanner (System.in); synchronized (locker) {System.out.println ("enter an integer") Int num= scanner.nextInt (); System.out.println ("num=" + num);}; t1.start () Thread T2 = new Thread () {@ Override public void run () {while (true) {synchronized (locker) {System.out.println ("Thread 2 acquires lock"); try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();}; t2.start ();}
Once the thread acquires the lock and does not release it, thread 2 will always block waiting at the lock.
Public static void main (String [] args) {Object locker1 = new Object (); Object locker2 = new Object (); Thread T1 = new Thread () {@ Override public void run () {Scanner scanner = new Scanner (System.in); synchronized (locker1) {System.out.println ("enter an integer") Int num= scanner.nextInt (); System.out.println ("num=" + num);}; t1.start () Thread T2 = new Thread () {@ Override public void run () {while (true) {synchronized (locker2) {System.out.println ("Thread 2 acquires lock"); try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();}; t2.start ();}
If it is not the same lock, there will be no competition and no mutual exclusion.
Public static void main (String [] args) {Object locker1 = new Object (); Object locker2 = new Object (); Thread T1 = new Thread () {@ Override public void run () {Scanner scanner = new Scanner (System.in); synchronized (locker1.getClass ()) {System.out.println ("enter an integer") Int num= scanner.nextInt (); System.out.println ("num=" + num);}; t1.start () Thread T2 = new Thread () {@ Override public void run () {while (true) {synchronized (locker2.getClass ()) {System.out.println ("Thread 2 acquires the lock"); try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();}; t2.start ();}
In this code, both threads compete against the class objects of locker1 and locker2, where both locker1 and locker2 are of type Object, and the corresponding objects are the same object.
The above is all the content of the article "sample Analysis of Java Thread Safety State". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.