开启线程 关闭线程

This commit is contained in:
liuhanqing
2025-06-11 17:50:33 +08:00
parent a29adb1ceb
commit e55cddf538
3 changed files with 65 additions and 12 deletions

View File

@@ -1,8 +1,8 @@
package com.ruoyi.schedule;
import com.ruoyi.schedule.plc.PlcRead;
import com.ruoyi.schedule.plc.domain.CustomThread;
import com.ruoyi.schedule.plc.domain.SsjDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@@ -11,23 +11,45 @@ import java.util.concurrent.ConcurrentHashMap;
@Component
public class ScheduleThread {
public PlcRead plcRead;
public CustomThread customThread;
/**
* 项目初始化启动
*/
@PostConstruct
public void init(){
public void init() {
ConcurrentHashMap<String, SsjDevice> list = new ConcurrentHashMap<>();
plcRead = new PlcRead(list);
PlcRead plcRead = new PlcRead(list);
Thread plcReadThread = new Thread(plcRead);
customThread = new CustomThread(plcReadThread, plcRead);
}
public void startAllThread(){
Thread plcReadThread = new Thread(plcRead);
plcReadThread.start();
/**
* 开始线程
*/
public void startAllThread() {
customThread.getThread().start();
}
public void stopAllThread(){
Thread plcReadThread = new Thread(plcRead);
plcReadThread.start();
/**
* 停止线程
*/
public void stopAllThread() {
stopThread(customThread);
}
/**
* 停止线程
*/
private void stopThread(CustomThread customThread) {
if (customThread.getThread() != null && customThread.getThread().isAlive()) {
((PlcRead)customThread.getRunnable()).stopReading();
try {
customThread.getThread().join(); // 等待线程结束
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

View File

@@ -10,6 +10,7 @@ import java.util.concurrent.ConcurrentHashMap;
public class PlcRead implements Runnable{
private final Map<String, SsjDevice> deviceMap;
private volatile boolean running = true;
public PlcRead(ConcurrentHashMap<String, SsjDevice> deviceMap) {
this.deviceMap = deviceMap;
@@ -17,7 +18,23 @@ public class PlcRead implements Runnable{
@Override
public void run() {
System.out.println("PLC Read thread is running...");
while (running && !Thread.currentThread().isInterrupted()) {
try {
// 模拟PLC读取操作
Thread.sleep(1000); // 模拟睡眠
// TODO: 实际读取PLC设备数据逻辑
} catch (InterruptedException e) {
// 捕获中断异常,退出循环
Thread.currentThread().interrupt(); // 重新设置中断标志
break;
}
}
}
public void stopReading() {
running = false;
Thread.currentThread().interrupt(); // 主动中断线程
}
}

View File

@@ -0,0 +1,14 @@
package com.ruoyi.schedule.plc.domain;
import com.ruoyi.schedule.plc.PlcRead;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomThread {
public Thread thread;
public Object runnable;
}