对电池电压新增单线程执行,优化修改
parent
bd7d4132e2
commit
3b492e7ea3
@ -0,0 +1,47 @@
|
||||
package com.xypower.mpmaster;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SingletonThread {
|
||||
private static SingletonThread instance;
|
||||
private Thread workerThread;
|
||||
private final AtomicBoolean isRunning = new AtomicBoolean(false);
|
||||
private final Object lock = new Object(); // 用于同步的锁对象
|
||||
private SingletonThread() {}
|
||||
|
||||
public static synchronized SingletonThread getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new SingletonThread();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void executeTask(Runnable task) {
|
||||
synchronized (lock) { // 加锁,确保检查+设置是一个原子操作
|
||||
if (isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
isRunning.set(true); // 立即标记为运行中,防止其他线程进入
|
||||
}
|
||||
|
||||
workerThread = new Thread(() -> {
|
||||
try {
|
||||
task.run();
|
||||
} finally {
|
||||
isRunning.set(false); // 任务完成后重置状态
|
||||
}
|
||||
});
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
public boolean isThreadRunning() {
|
||||
return isRunning.get();
|
||||
}
|
||||
|
||||
public void waitForCompletion() throws InterruptedException {
|
||||
if (workerThread != null) {
|
||||
workerThread.join();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue