0
我正在開發我的Spring引導應用程序,至此 得到兩個請求:/ start和/ stop。 我需要爲所有客戶端請求創建一個共享線程。Spring Boot共享線程
當客戶端收到第一個請求「/ start」時,app會創建一個由局部變量T1共享的線程。
當接收到第二個請求「/ stop」時,app會設置線程「停止」的布爾變量來停止它,線程應該停止。
下一個代碼是否爲此共享線程提供了安全性? 我應該使用線程對象的局部變量還是需要 以另一種方式做到這一點?
package com.direct.webflow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
public class WebApp {
ThreadDemo T1;
@RequestMapping("/start")
@ResponseBody
String start() {
synchronized(this){
if (T1 == null || T1.stopped) {
T1= new ThreadDemo("Thread-1");
T1.start();
} else {
return "Already started!";
}
}
return "Thread started!";
}
@RequestMapping("/stop")
@ResponseBody
String end() {
if (T1 == null) {
System.out.println("Not started!");
return "Not started!";
} else if (!T1.stopped) {
T1.stopped=true;
System.out.println("Trying to stop!");
return "Stopped!";
} else {
return "Already stopped!";
}
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApp.class, args);
}
}
package com.direct.webflow;
public class ThreadDemo extends Thread {
private Thread t;
private String threadName;
public volatile boolean stopped=false;
ThreadDemo(String name){
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
int i=0;
System.out.println("Running " + threadName);
while (!stopped) {
System.out.println("Thread: " +this.isInterrupted()+ threadName + ", " + i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread: STOP!");
break;
}
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start()
{
stopped=false;
System.out.println("Starting " + threadName);
if (t == null)
{
t = new Thread (this, threadName);
t.start();
}
}
}
您不應該首先在容器中啓動/停止線程。 –