【发布时间】:2014-04-17 16:14:49
【问题描述】:
我有一个单实例线程类。
public class LogThread extends Thread{
private static LogThread instance = null;
private volatile boolean isRunning = false;
private final static Object instanceLock = new Object();
public static synchronized LogThread getInstance(){
synchronized(instanceLock){
if(instance == null)
instance = new LogThread();
}
return instance;
}
@Override
public run(){
//Doing some run stuff
//Once run is finished
synchronized(instanceLock){
isRunning = false;
instance = null;
}
}
@Override
public synchronized void start() {
synchronized (instanceLock){
if(!isRunning){
isRunning = true;
super.start();
}
}
}
}
每次获取实例时,我都会从另一个线程调用 start,并且每隔一段时间,我会在 com.......LogThread.start 中收到 IllegalThreadStateException,第 x 行线程已经启动。
如果我在启动线程之前设置了 isRunning 并基于 instanceLock 同步它,如何启动线程。
编辑:: 我已将我的 getInstance() 编辑到以下:
public static synchronized LogThread getInstance(){
synchronized(instanceLock){
if(instance == null){
instance = new LogThread();
instance.start();
}
}
}
它应该停止任何尝试启动已经启动的线程。
【问题讨论】:
-
在您的情况下实际上应该是不可能的,您是否曾经将
isRunning设置回false?例如。在run() -
是的,我将 isRunning 设置为 false,就在我在同步线程中将实例设置为 null 之前,将发布更新的代码
标签: java android multithreading thread-safety