請注意,當使用 runnable 介面時,您不能直接建立所需類的對象並運行它;必須從 Thread 類的一個執行個體內部運行它。許多程式員更喜歡 runnable 介面,因為從 Thread 類繼承會強加類層次。程式碼範例如下:package job;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainJob implements Runnable {
private String path = null;
public MainJob(String filePath) {
this.path = filePath;
}
public void run() {
while (true) {
try {
write("Write " + (new SimpleDateFormat("yyyyMMddHHmmss")).format((new Date())));
Thread.sleep(3000L);
} catch (InterruptedException e) {
utils.Log.add(this).error(e.getMessage());
}
}
}
// 當需要加鎖時,只需在void前加synchronized即可
private void write(String msg) {
try {
String path = String.format("%slogs\\msg.txt", this.path);
FileWriter fw = new FileWriter(path, true);
fw.write(String.format("%s - %s\r\n", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.format((new Date())), msg));
fw.flush();
fw.close();
} catch (IOException ex) {
utils.Log.add(this).error(ex.getMessage());
}
}
}
在JSP中調用
<%
String filePath = this.getServletContext().getRealPath("/");
Thread job = new Thread(new MainJob(filePath));
job.start();
%>