import java.io.file;
import java.io.ioexception;
import java.io.randomaccessfile;
import java.nio.channels.filechannel;
import java.nio.channels.filelock;
/**
* @author dbj
*
*/
public class mythreadinfowritor {
private string filename;
/**
*
*/
public mythreadinfowritor(string filename) {
this.filename = filename;
}
public void write(mythreadinfo tinfo) {
randomaccessfile out = null;
file file = new file(this.filename);
try {
if (!file.exists()) {
file.createnewfile();
out = new randomaccessfile(file, rw);
}
out = new randomaccessfile(file, rw);
filechannel fcout = out.getchannel();
filelock flout = null;
while (true) {
try {
flout = fcout.lock();
break;
} catch (exception e) {
system.out.println(其他线程正在操作该文件,当前线程休眠1000毫秒);
try {
thread.sleep(1000);
} catch (interruptedexception e1) {
e1.printstacktrace();
}
}
}
long filelength = out.length();
out.seek(filelength);
out.write(tinfo.tostring().getbytes(utf8));
flout.release();
fcout.close();
out.close();
out = null;
} catch (ioexception e) {
file.deleteonexit();
system.out.println(exception encountered: + e);
}
}
}