在Java/J2EE(比如Struts2/Spring/Hibernate)实际项目中有用过多线程吗?比如java.util.concurrent包?
都实现什么功能?用了那些API?
------解决思路----------------------
用的比较多的是线程池,线程参数不要共享,由多线程调度程序分配数据。
------解决思路----------------------
java.util.concurrent.Executors
------解决思路----------------------
Concurrency Utilities for Java EE sample:
/**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package javaeetutorial.concurrency.jobs.service;
import java.util.UUID;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
/**
* @author markito
*/
@Stateless
@Path("/JobService")
public class JobService {
private final static Logger logger = Logger.getLogger(JobService.class.getCanonicalName());
// http header to check for valid tokens
private final static String API_TOKEN_HEADER = "X-REST-API-Key";
@Resource(lookup = "MES_High")
private ManagedExecutorService highPrioExecutor;
@Resource(lookup = "MES_Low")
private ManagedExecutorService lowPrioExecutor;
@EJB
private TokenStore tokenStore;
@GET
@Path("/token")
public Response getToken() {
// static token + dynamic token
final String token = "123X5-" + UUID.randomUUID().toString();
tokenStore.put(token);
return Response.status(200).entity(token).build();
}
@POST
@Path("/process")
public Response process(final @HeaderParam(API_TOKEN_HEADER) String token,
final @QueryParam("jobID") int jobID) {
try {
if (token != null && tokenStore.isValid(token)) {
logger.info("Token accepted. Execution with high priority.");
highPrioExecutor.submit(new JobTask("HIGH-" + jobID));
} else {
logger.log(Level.INFO, "Invalid or missing token! {0}", token);
// requests without token, will be executed but without priority
lowPrioExecutor.submit(new JobTask("LOW-" + jobID));
}
} catch (RejectedExecutionException ree) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Job " + jobID + " NOT submitted. " + ree.getMessage()).build();
}
return Response.status(Response.Status.OK).entity("Job " + jobID + " successfully submitted.").build();
}
static class JobTask implements Runnable {
private final String jobID;
private final int JOB_EXECUTION_TIME= 10000;
public JobTask(String id) {
this.jobID = id;
}
@Override
public void run() {
try {
logger.log(Level.INFO, "Task started {0}", jobID);
Thread.sleep(JOB_EXECUTION_TIME); // 5 seconds per job
logger.log(Level.INFO, "Task finished {0}", jobID);
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
------解决思路----------------------
/**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package javaeetutorial.concurrency.jobs.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
/**
* @author markito
*/
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Singleton
public class TokenStore implements Serializable {
private final List<String> store;
public TokenStore() {
this.store = new ArrayList<>();
}
@Lock(LockType.WRITE)
public void put(String key) {
store.add(key);
}
@Lock(LockType.READ)
public boolean isValid(String key) {
return store.contains(key);
}
}
------解决思路----------------------
线程池 的调用 。
------解决思路----------------------
怕说的不详细,百度了下,这个比较详细 http://www.cnblogs.com/riskyer/p/3263032.html
如果对线程比较了解,只想看线程池部分,可以直接看“Java线程:新特征-线程池”章节
------解决思路----------------------
不需要 。平台做多线程,http连接池,数据库连接池等,而90%的应用(你开发的)都是单线程的