【发布时间】:2013-03-27 02:31:14
【问题描述】:
我的测试程序要求输入一个字符串并每 2 秒打印一次。我已经阅读了一些关于 java 内存模型或线程如何不立即更新主内存上的变量的内容。
我已尝试使用 volatile 和 static 属性。同步修改了变量line 的代码块。使用wait()/notifi() 更改变量和其他一些变量。如何将line 分配为参考而不是值?我是否使用了我尝试错误的方法?为什么对象在充当监视器时可以保持完美同步,而在充当指针时却不能?
public class TestSharedVariable {
static String line= "";
public static void main(String[] args) {
// For reading from keyboard
Scanner keyboard = new Scanner(System.in);
Printer p = new Printer(line);
p.start();
// Reads a line from keyboard into the shared variable
while(!line.equals("quit")){
line = keyboard.nextLine();
}
}
}
class Printer extends Thread{
private volatile String line;
public Printer(String palabra){
this.line = palabra;
}
/* Prints the line each 2 sec */
@Override
public void run(){
while(!line.equals("quit")){
try {
sleep(2000);
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(this.getName() + ": " + line);
}
}
}
输出:
Thread-0:
asdf
Thread-0:
Thread-0:
【问题讨论】:
标签: java multithreading asynchronous concurrency