62,614
社区成员
发帖
与我相关
我的任务
分享
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
public class NoVisibility {
private static class ReaderThread extends Thread {
private WriteThread writeThread;
ReaderThread(WriteThread wt){
writeThread = wt;
}
@Override
public void run() {
while (!writeThread.ready) {
Thread.yield();
}
System.out.println(writeThread.number);
}
}
private static class WriteThread extends Thread{
public boolean ready;
public int number;
@Override
public void run() {
number = 42;
ready = true;
}
}
public static void main(String[] args) {
for (int i = 0; i <1000; i++){
WriteThread wt = new WriteThread();
new ReaderThread(wt).start();
wt.start();
}
}
}