restful 的线程安全问题

本文介绍了一个简单的RESTful服务实现,该服务提供了一个计数器功能,通过GET请求可以获取当前计数器的值并使其递增,同时支持设置计数器的初始值。
package com.ws.service.syn;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;


@Path("counter")
public class Counter {


public int counter = 0;
@GET
@Path("/count")
public String getCount(){
counter++;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return String.valueOf(counter);
}
public int get(){
return counter;
}
public void set(int num){
this.counter = num;
}
@GET
@Path("/hello")
public String hello(){
return "xjiewenbo";
}
@GET
@Path("/{num}")
@Produces("text/plain")
public String getCounter(@PathParam("num")String num){
set(Integer.parseInt(num));

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return String.valueOf(get());
}

}


public static void main(String[] args) throws IOException {
        URI ServerURI=UriBuilder.fromUri("http://localhost/").port(9999).build();
    startServer(ServerURI);
        System.out.println("服务已启动,请访问:"+ServerURI);
    }    

    protected static SelectorThread startServer(URI serverURI) throws IOException {
        final Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("com.sun.jersey.config.property.packages","com.ws.service.syn");
        System.out.println("Grizzly 启动中...");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(serverURI, initParams);     
        return threadSelector;
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值