我有一个启动线程的程序。在构造函数中,我传递一个volatile布尔值,但是当在主线程中更改变量时,此更改不会反映在线程中。
我在主类中声明了以下内容。
private static volatile boolean sendbuff1;
private static volatile boolean sendbuff2;
private static volatile boolean closeSession;
并开始这样的线程。
try{
Thread uploader = new Thread(new appendObj(buffer1loc, buffer2loc, sendbuff1, sendbuff2, closeSession));
uploader.start();
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
稍后在main函数中,sendbuff1从false设置为true,但线程中的sendbuff1不会改变。我把它打印出来并且它仍然是假的。
在appendObj线程中,
while(!closeSession) {
if (sendbuff1) {
//append
System.out.println("sendbuff 1 changed");
try {
PrintWriter tobuff1 = new PrintWriter(new File(buffer1loc));
try1.appendFile(buffer1loc);
tobuff1.write("");
tobuff1.close();
sendbuff1 = false;
} catch (Exception e) {
System.out.println("error caught print writing send buff 2");
e.printStackTrace();
}
}
if (sendbuff2) {
System.out.println("sendbuff 2 changed");
try {
PrintWriter tobuff2 = new PrintWriter(new File(buffer2loc));
try1.appendFile(buffer2loc);
tobuff2.write("");
tobuff2.close();
sendbuff2 = false;
} catch (Exception e) {
System.out.println("error caught print writing send buff 2");
e.printStackTrace();
}
}
}
不知道我做错了什么