JAVA多线程2
请注意,当使用 runnable 接口时,您不能直接创建所需类的对象并运行它;必须从 Thread 类的一个实例内部运行它。许多程序员更喜欢 runnable 接口,因为从 Thread 类继承会强加类层次。代码示例如下:
在JSP中调用
<%
String filePath = this.getServletContext().getRealPath("/");
Thread job = new Thread(new MainJob(filePath));
job.start();
%>
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());
}
}
}
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();
%>