我有一个类boolean
变量isbeingwritten
。它会跟踪文件是否正在写入。这个类的一个函数调用一些写入文件的线程。这些将首先检查isbeingwritten
变量的值,如果它是false
,则将其设置为true
并开始写入,否则它们将等待。在写作结束时,他们会将值更改回false
。如果这个变量是volatile
?变量应该变得易变吗?
class A
{
public boolean isbeingwrittenfalse;
public void func()
{
new thread1();
new thread2();
}
class thread1 implements Runnable
{
Thread t;
thread1()
{
t=new Thread (this);
t.start();
}
public void run()
{
while(isbeingwritten);
isbeingwritten=true;
//wrrite very long string
isbeingwritten=false;
}
}
class thread2 implements Runnable
{
Thread t;
thread2()
{
t=new Thread (this);
t.start();
}
public void run()
{
while(isbeingwritten);
isbeingwritten=true;
//wrrite very long string
isbeingwritten=false;
}
}
下才是正确的解决
public class XSSThread implements Runnable {
Thread xt;
public void init() {
xt = new Thread(this);
xt.start();
}
public void run() {
new Thread1().init();
new Thread2().init();
}
public synchronized void saveToFile(String a) {
File aFile = new File("filename.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(aFile, aFile.exists()));
out.write(a + "\r\n");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Thread1 extends XSSThread implements Runnable{
Thread xt1;
public void init() {
xt1 = new Thread(this);
xt1.start();
}
public void run() {
String a;//very long string
saveToFile(a);
}
}
public class Thread2 extends XSSThread implements Runnable {
Thread xt2;
public void init() {
xt2 = new Thread(this);
xt2.start();
}
public void run() {
String a;//very long string
saveToFile(a);
}
}
现在同步正确。但是,您不应该完全改变问题,因为这会让其他人难以将其与答案匹配。请再次更改,以便它包含原始问题和修订问题。 – nosid 2013-05-11 10:09:39