multithreading - Java - Stop thread with shared object -


i want use shared object stop threads. code wrote simple.

the main method creates , starts threads, waits 800 ms, after that, sets attribute of shared object "false".

the threads in busywait if attribute of shared object "true".

the code doesn't work (an infinite loop occurs), seems there mutual exclusion problem can't explain, threads read attribute.

can explain me this, please? :)

main

public class sharedresthreadext { public static void main(string args[]) {     bodythread[] my_threads = new bodythread[5];                     sharedrsrc sh_resource = new sharedrsrc(true);   // shared object dec , alloc      (int = 0; < my_threads.length; i++) {    // creation , start threads         my_threads[i] = new bodythread(sh_resource);                  my_threads[i].start();     }      try{         thread.sleep(800);          // wait 800 millisec          sh_resource.setflag(false);  //sets shared object attribute false     }     catch(interruptedexception e){} } } 

threads body

class bodythread extends thread {                     private sharedrsrc sr;          public bodythread(sharedrsrc sr){     this.sr = sr; }  @override public void run() {     system.out.println("thread: " + getid() + " starts exec.");     while(sr.getflag()){}              // busywait if shared object attributeis true       system.out.println("thread: " + getid() + " stopped exec."); } } 

shared object

class sharedrsrc{ private boolean flag;  public sharedrsrc(boolean flag){     this.flag = flag; } public boolean getflag(){     return this.flag; } public void setflag(boolean flag){     this.flag = flag; }  } 

change shared object

from:

class sharedrsrc{ private boolean flag;  public sharedrsrc(boolean flag){     this.flag = flag; } public boolean getflag(){     return this.flag; } public void setflag(boolean flag){     this.flag = flag; }  } 

to:

   class sharedrsrc{    private volatile boolean flag;      public sharedrsrc(boolean flag){         this.flag = flag;     }     public boolean getflag(){         return this.flag;     }     public void setflag(boolean flag){         this.flag = flag;     }      } 

or can declare variable directly in sharedresthreadext below.

private static volatile boolean flag= false; 

if dont want use volatile second option use synchronized


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -