2016-03-08 53 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控制器是單例,你可以像使用這裏所做的那樣使用成員變量。