Multi-Threaded 7---The volatile keyword, flushes the thread workspace memory into main memory, that is, stays in sync

Source: Internet
Author: User
Tags flushes

1. Change to static also not private static Boolean isrunning = true; The volatile keyword is primarily used for the visibility of thread variables between multiple threads

1  Public classRunthreadextendsthread{2     Private volatile  BooleanIsRunning =true;3      Public voidSetrunning (Booleanisrunning) {4System.out.println (Thread.CurrentThread (). GetName () + Thread setrunning);5          This. isrunning =isrunning;6     }7 8      Public voidrun () {9System.out.println (Thread.CurrentThread (). GetName () + "Enter the Run method ...");Ten          while(isrunning) { One             //System.out.println (Thread.CurrentThread (). GetName () + "thread isrunning"); A         } -System.out.println (Thread.CurrentThread (). GetName () + "thread termination"); -     } the  -      Public Static voidMain (string[] args)throwsException { -Runthread RT =NewRunthread (); - Rt.start (); +Thread.Sleep (3000); -Rt.setrunning (false); +System.out.println (Thread.CurrentThread (). GetName () + "thread isrunning value is set to False"); AThread.Sleep (100); atSystem.out.println (Thread.CurrentThread (). GetName () + "::" +rt.isrunning); -     } -     /*without the volatile keyword, the isrunning in the main memory will not be refreshed and will always be true. So the thread does not terminate, plus it flushes the working memory variables of the RT thread to the main memory - * Thread-0 into the Run method ... - Main thread setrunning - main thread isrunning value is set to False in Main::false -      */ to}
View Code

Multi-Threaded 7---The volatile keyword, flushes the thread workspace memory into main memory, that is, stays in sync

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.