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 keywords and methods in Java Thread

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

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you the "example analysis of keywords and methods in Java threads", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let me lead you to study and learn about "sample analysis of keywords and methods in Java threads".

1. The volatile keyword 1 volatile ensures the visibility of memory.

When the code writes a volatile-decorated variable

Change the value of the copy of the volatile variable in the thread's working memory

Refresh the value of the changed copy from working memory to main memory

When the code reads the variables modified by volatile

Read the latest value of the volatile variable from the main memory into the thread's working memory

Read a copy of the volatile variable from working memory

Static class Counter {public int flag = 0;} public static void main (String [] args) {Counter counter = new Counter (); Thread T1 = new Thread () {@ Override public void run () {while (counter.flag = = 0) {} System.out.println ("end of loop") }; t1.start (); Thread T2 = new Thread () {Scanner scanner = new Scanner (System.in); System.out.println ("Please enter an integer:"); counter.flag = scanner.nextInt (); t2.start ()

The expected results are:

Thread 1 first enters the loop state, and thread 2 reads an integer entered by the user. Thread 1 terminates as the user enters an integer that is not 0.

Actual effect:

After the input of thread 2, the thread 1 loop did not end

2, compiler optimization problem

In the core code of thread 1, the loop does nothing, repeatedly and quickly performs the comparison operations in the loop conditions.

First read the value of flag from memory to CPU

Compare the relationship between this value and 0 in CPU

The compiler decided that the loop in this logic did nothing but read memory frequently, so the compiler optimized the operation of reading memory. After the data in memory was read to CPU for the first time, the sequenced memory was not really read from memory, but directly from the CPU.

The compiler thinks that the flag has not changed, but in fact, if there is no change in the current thread, the compiler will not be aware that other threads have modified the flag.

Static class Counter {public volatile int flag = 0;} public static void main (String [] args) {Counter counter = new Counter (); Thread T1 = new Thread () {@ Override public void run () {while (counter.flag = = 0) {} System.out.println ("end of loop") }; t1.start (); Thread T2 = new Thread () {Scanner scanner = new Scanner (System.in); System.out.println ("Please enter an integer:"); counter.flag = scanner.nextInt (); t2.start ()

After adding volatile, the read operation on this memory must be read from memory.

Without volatile, the read operation may not be read from memory, but the old value may be read from CPU, which is uncertain.

There are essential differences between volatile and synchronized.

Synchronized guarantees atomicity, while volatile guarantees memory visibility.

Synchronized can guarantee both atomicity and memory visibility.

II. Wait and notify

Because the execution between threads is preemptive, the order of execution between threads is difficult to predict. But in actual development, sometimes we want to coordinate the execution sequence of multiple threads reasonably.

1dint wait () method

What wait does:

Causes the currently executing thread to wait. (put the thread in the waiting queue)

Release the current lock

Wake up when certain conditions are met and try to acquire the lock again.

Wait should be used with synchronized. Using wait without synchronized will throw an exception directly.

Conditions for wait to end waiting:

Other threads call the object's notify method.

The wait wait time timed out (the wait method provides a version with the timeout parameter to specify the wait time).

Other threads call the waiting thread's interrupted method, causing wait to throw an InterruptedException exception.

Public static void main (String [] args) throws InterruptedException {Object object = new Object (); synchronized (object) {System.out.println ("wait before"); object.wait (); System.out.println ("wait after");}}

It is equivalent to a person going to ATM to withdraw money, finding that there is no money in ATM, and then blocking waiting (not participating in the competition for subsequent locks)-- wait

When the bank staff comes to deliver the money, you can withdraw the money-- notify

2. The method of recording ()

The notify method wakes up the waiting thread.

The method notify () is also called in a synchronization method or synchronization block, which notifies other threads that may be waiting for the object lock, notifies notify, and causes them to reacquire the object lock for the object.

If there are multiple threads waiting, a thread scheduler randomly picks out a thread in the wait state. (there is no "first come, first come")

After the notify () method, the current thread does not release the object lock immediately, but not until the thread executing the notify () method finishes executing the program, that is, after exiting the synchronous code block.

Public static void main (String [] args) {Object locker = new Object (); Thread T1 = new Thread () {@ Override public void run () {synchronized (locker) {while (true) {System.out.println ("wait start") Try {locker.wait ();} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("wait end") }; t1.start (); Thread T2 = new Thread () {Scanner scanner = new Scanner (System.in); System.out.println ("enter an integer to continue"); int num = scanner.nextInt () System.out.println ("notify start"); locker.notify (); System.out.println ("notify end"); t2.start ();}

3. The notifyAll () method

The notify method simply wakes up a waiting thread.

Use the notifyAll method to wake up all waiting threads at once.

The above is all the content of the article "sample Analysis of keywords and methods in Java threads". 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report