我在程序中使用了多线程,但是只用run方法,没有关闭,请问这个线程什么时候会关闭,如果时间久了,会导致内存溢出吗?我的代码为:
public void readData() {
// 在新线程中调用耗时操作
new Thread() {
public void run() {
writeLog();
}
}.start();
}public void riteLog(){
FileWriter fw =null;
try {
fw=new FileWriter("d:/tt.txt");
fw.write("test!!!");
}catch (Exception e) {
MutilLogWriter.write(2, "", " makeRealData error:" + e.getMessage());
}finally{
try {
fw.flush();
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }如果想在程序中设置写完日志后将线程关闭,可以通过在run方法中用boolean变量判断吗?如改成:
public void readData() {
// 在新线程中调用耗时操作
new Thread() {
boolean bol=true;
public void run() {
while(bol){
bol=writeLog();
}
}
}.start();
}public boolean writeLog(){
boolean bol=true;
FileWriter fw =null;
try {
fw=new FileWriter("d:/tt.txt");
fw.write("test!!!");
}catch (Exception e) {
MutilLogWriter.write(2, "", " makeRealData error:" + e.getMessage());
}finally{
try {
fw.flush();
fw.close();
bol=false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return bol; }
public void readData() {
// 在新线程中调用耗时操作
new Thread() {
public void run() {
writeLog();
}
}.start();
}public void riteLog(){
FileWriter fw =null;
try {
fw=new FileWriter("d:/tt.txt");
fw.write("test!!!");
}catch (Exception e) {
MutilLogWriter.write(2, "", " makeRealData error:" + e.getMessage());
}finally{
try {
fw.flush();
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }如果想在程序中设置写完日志后将线程关闭,可以通过在run方法中用boolean变量判断吗?如改成:
public void readData() {
// 在新线程中调用耗时操作
new Thread() {
boolean bol=true;
public void run() {
while(bol){
bol=writeLog();
}
}
}.start();
}public boolean writeLog(){
boolean bol=true;
FileWriter fw =null;
try {
fw=new FileWriter("d:/tt.txt");
fw.write("test!!!");
}catch (Exception e) {
MutilLogWriter.write(2, "", " makeRealData error:" + e.getMessage());
}finally{
try {
fw.flush();
fw.close();
bol=false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return bol; }
你的线程new的太多了
daemon thread是守护线程,它在程序的背后提供服务的线程,它自贯穿程序始终,当程序结束了,它也就结束了,如果还有非守护线程的线程在执行,它就不会结束。
// 在新线程中调用耗时操作
new Thread() {
public void run() {
writeLog();
} }.start();
} public void writeLog() {
FileWriter fw = null;
try {
fw = new FileWriter("d:/tt.txt ");
fw.write("test!!! ");
}
catch (Exception e) {
MutilLogWriter.write(2, " ", " makeRealData error: " + e.getMessage());
}
finally {
try {
fw.flush();
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
你可以写个测试代码
for (int i=0; i<INTEGER.MAX_VALUE; i++) {
System.out.println(i); //看看多少次调用会发生这种情况,
//然后比较一下一次交易会发生写入的日志次数
readData();
}