我有一个类,其中有一个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);
}
}