2016-03-08 218 views
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(); 
      } 
     } 

    } 
+0

您不应该首先在容器中启动/停止线程。 –

回答

0

这非常接近。您需要将同步(此)块添加到您的控制器中end()方法。否则,如果/ stop和/ start被同时调用,您可能会遇到竞争状况。

由于Spring控制器是单例,你可以像使用这里所做的那样使用成员变量。