无法获得这两个线程的所需输出

时间:2016-07-07 09:30:00

标签: java multithreading volatile

我正在尝试在java中实现volatile变量,并且我首先创建了一个没有volatile变量的程序

public class test extends Thread 
{
private int value = 1;
@Override
public void run(){
if(Thread.currentThread().getName().equals("read thread"))  
  read();
    if(Thread.currentThread().getName().equals("write thread"))
    {
      try { 
          Thread.sleep(1000);
      } catch (InterruptedException ex) {
          Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
      }
  changeValue();
    }  
}

void read() {
System.out.println(Thread.currentThread().getName() +" "+ value);

try {
  Thread.sleep(2000);
} catch (InterruptedException e) {
}

// If another thread called changeValue()
// in the meantime the next print instruction is
// guaranteed to write "2"
System.out.println(Thread.currentThread().getName() +" "+ value);
}

public void changeValue() {
 value = 2;
}

public static void main(String args[]){
   test obj=new test();
   Thread r=new Thread(obj);
   Thread w=new Thread(obj);
   r.setName("read thread");
   w.setName("write thread");
   r.start(); 
   w.start();      
}
} 

o / p不是预期的..读取线程正在采用最新值..由写入线程完成的更改值,这应该仅在值为volatile时

提前致谢

0 个答案:

没有答案