[英]Spring Boot shared thread
我正在開發我的Spring引導應用程序,它有兩個請求:/ start和/ stop。 我需要為所有客戶端請求創建一個共享線程。
當從客戶端收到第一個請求“ / start”時,app將創建一個由本地變量T1共享的線程。
當收到第二個請求“ / stop”時,應用程序將設置線程“ stopped”的布爾變量以將其停止,線程應停止。
下一個代碼是否為此共享線程提供了安全? 我應該將局部變量用於線程對象還是需要通過其他方式來實現?
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 ();
}
}
}
這非常接近。 您需要在控制器end()方法中添加synced(this)塊。 否則,如果同時調用/ stop和/ start,則可能會出現競爭狀況。
由於Spring控制器是單例的,因此可以像在此一樣使用成員變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.