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

The use of the Java modifier volatile

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "the usage of the Java modifier volatile". In the daily operation, I believe that many people have doubts about the usage of the Java modifier volatile. The editor has consulted all kinds of materials and sorted out the simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about the usage of the Java modifier volatile! Next, please follow the editor to study!

A Volatile-decorated member variable forces the value of the member variable to be reread from shared memory each time it is accessed by a thread. Also, when a member variable changes, the thread is forced to write back the change value to shared memory. So that at any time, two different threads always see the same value of a member variable. A volatile object reference may be null. Package niukewang;public class volatile_Test {public static void main (String args []) {MyRunnable r = new MyRunnable (); Thread T1 = new Thread (r); t1.start (); try {Thread.sleep (2); r.stopThread ();} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () } class MyRunnable implements Runnable {private volatile boolean active; public void run () {active = true; while (active) / / first line {/ / code System.out.println ("Print the line");}} public void stopThread () {System.out.println ("Set to false"); active = false / / second line}} only when stopThread is called and ative is set to false, then the thread gets the value of false and stops the output of the content in the first line. At this point, the study on the use of the Java modifier volatile is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report