我有一個類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