龙空技术网

SpringMVC是如何处置线程安全

马克java社区 135

前言:

今天同学们对“netmvc线程”大概比较关怀,兄弟们都需要剖析一些“netmvc线程”的相关资讯。那么小编在网络上搜集了一些关于“netmvc线程””的相关内容,希望咱们能喜欢,兄弟们一起来学习一下吧!

线程安全

一般情况下,@Controller是单例的,和Servlet那时是一样的,参见我的Servlet的第二章处理线程安全的问题。

例5.1:

package com;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.context.ServletConfigAware;

import org.springframework.web.context.ServletContextAware;

import org.springframework.web.context.support.WebApplicationContextUtils;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.support.RequestContextUtils;

import com.jspsmart.upload.File;

import com.jspsmart.upload.Files;

import com.jspsmart.upload.SmartUpload;

import com.jspsmart.upload.SmartUploadException;

@Controller

public class HelloWorldController implements ServletConfigAware,ServletContextAware {

private ServletContext servletContext;

@Override

public void setServletContext(ServletContext arg0) {

this.servletContext = arg0;

}

private ServletConfig servletConfig;

@Override

public void setServletConfig(ServletConfig arg0) {

this.servletConfig = arg0;

}

int bookNum=20;

@RequestMapping("/MultiThread.do")

public void downloadF(HttpServletRequest request, HttpServletResponse response,

HttpSession sesssion) throws IOException, ServletException {

PrintWriter pw = response.getWriter();

while (bookNum>0){

onlySellOne(pw);

}

}

synchronized void onlySellOne(PrintWriter pw) throws IOException {

if (bookNum > 0) {

pw.println(Thread.currentThread().getName()

+ " before" + bookNum);

pw.flush();

bookNum--;

try {

Thread.sleep(2000);

} catch (Exception e) {

}

pw.println(Thread.currentThread().getName()

+ " after " + bookNum);

pw.flush();

}

}

}

篇幅有限更多请见扩展链接。。。。。

标签: #netmvc线程