在多线程中,为什么这两种写法有非常大的结果性的区别
public class Run implements Runnable {
public static boolean isContinuePrint = true;
public boolean isContinuePrint() {
return isContinuePrint;
}
public void setContinuePrint(boolean isContinuePrint) {
this.isContinuePrint = isContinuePrint;
}
public void printStringMethod() {
while (isContinuePrint == true) {
System.out.println("run printStringMethod threadName="
+ Thread.currentThread().getName());
}
}
@Override
public void run() {
printStringMethod();
}
public static void main(String[] args) {
try {
//差不多的代码,为什么我不死循环!
Run printStringService = new Run();
new Thread(printStringService).start();
Thread.sleep(1000);
System.out.println("我要停止它!stopThread="
+ Thread.currentThread().getName());
Run.isContinuePrint = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Test {// volatile
private static boolean stop = false;
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stop) {
i++;
// System.out.println("hello");
}
}
});
t.start();
Thread.sleep(1000);
System.out.println("Stop Thread");
stop = true;
}
}
就是多线程的示例,为什么一个不死循环一个死循环呢?我感觉是变量在内存的管理,但说不清,请教一下各位!