【发布时间】:2015-02-28 04:56:59
【问题描述】:
我是信号量的新手,我有任何问题。我有一个线程,它从文本文件 A 开始并读取行并将它们写入其他文本文件 B。我编写了这段代码,但我不确定线程是否阻塞关键部分并正确同步。因为和其他线程可以操作这些文件。
public static void main(String[] args) {
Thread thread = new Thread(new ThreadManager());
thread.start();
}
线程类:
public class ThreadManager extends Thread {
private Semaphore semaphore;
public ThreadManager() {
this.semaphore = new Semaphore(1);
}
public void run() {
try {
this.semaphore.acquire();
BufferedReader br = null;
String line;
String fileNme = "threadLog.txt";
ArrayList<String> fileLines = new ArrayList<String>();
int numLine = 0;
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = null;
PrintWriter out = null;
try {
fis = new FileInputStream(fileNme);
// output
FileOutputStream fos = new FileOutputStream(outFile);
out = new PrintWriter(fos);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
try {
while ((line = in.readLine()) != null) {
fileLines.add(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!fileLines.isEmpty()) {
int middleLine = (int) Math.round(fileLines.size() / 2);
fileLines.add(middleLine, Thread.currentThread().getName());
for (int i = 0; i < fileLines.size(); i++) {
out.println(fileLines.get(i));
}
out.flush();
out.close();
try {
in.close();
new File(fileNme).delete();
outFile.renameTo(new File(fileNme));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.semaphore.release();
} catch (InterruptedException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
【问题讨论】:
-
考虑使用
using {...}块。 -
考虑使用同步。不过,这不会阻止 其他 代码接触文件。
-
@Scary Wombat Synchronized 只允许一个执行线程同时访问资源。信号量允许最多 n 个(您可以选择 n 个)执行线程同时访问资源。但是信号量对我的任务来说是不必要的吗?
-
@Fortran 不清楚您的任务是什么。例如,您真的希望多个线程同时写入同一个文件吗?
-
@Fortran 您只指定了带有 1 个执行线程的信号量,在我看来这会导致复杂的同步
标签: java multithreading semaphore