我编写了一个用于创建记录的内部类CreateRecord,当调用create方法时,稍后将instance.It作为一个任务提交给executor。我是否每次都要创建一个内部类来表示要执行的任务(例如deleteRecord、updateRecord)。有没有人能建议一个更好的方法。
ExecutorService exec=new ThreadPoolExecutor(corePoolSize,maxPoolSize,
keepAlive,TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>());
public void create(String str ) throws RemoteException
{
exec.execute(new CreateRecord(str));
}
class CreateRecord implements Runnable
{
private String Id;
public CreateRecord(String Id)
{
this.Id=Id;
}
@Override
public void run()
{
System.out.println("Record creation in progress of: "+Id+
" by thread: "+Thread.currentThread().getName());
Record rec=new Record(Id);
map.put(Id, rec);
}
}发布于 2014-01-22 04:51:31
您可以只实例化一个Runnable,而不是声明一个新类。在Java中,这些被称为匿名内部类。
public void create(final String id) throws RemoteException
{
exec.execute(new Runnable()
{
@Override
public void run()
{
System.out.println("Record creation in progress of: "+id+" by thread: "+Thread.currentThread().getName());
Record rec=new Record(id);
map.put(id, rec);
}
});
}发布于 2014-01-22 04:53:54
ExecutorService需要Runnable对象。Runnable对象必须是类的实例。
有两个选项:
(1)参数化您的Runnable类,使其能够做多件事。但这违反了一些好的设计原则。
(2)使用匿名类:
public void create(final String id) throws RemoteException {
exec.execute(new Runnable() {
@Override
public void run() {
System.out.println("Record creation in progress of: "+id+" by thread: "+Thread.currentThread().getName());
Record rec = new Record(id);
map.put(id, rec);
}
});
}请注意,必须将id和您希望从Runnable外部使用的任何其他变量声明为final。
仅供参考,
System.out.printf(
"Record creation in progress of: %d by thread: %s%n",
id,
Thread.currentThread().getName()
);更易读一些。
发布于 2014-01-22 04:50:30
像现在这样创建一个类,比如Record,并在构造函数中指定一个额外的int或String参数,可以在run()方法中使用它来决定要做什么-即根据第二个参数的值更新、删除或添加一条记录。如下所示:
class Record implements Runnable
{
private String id;
private String operation;
public Record(String id, String operation)
{
this.id = id;
this.operation = operation;
}
@Override
public void run()
{
if(operation.equals("update")) {
//code for updating
} else if(operation.equals("insert")) {
System.out.println("Record creation in progress of: "+Id+
" by thread: "+Thread.currentThread().getName());
Record rec=new Record(id);
map.put(id, rec);
} else {//if(operation.equals("delete"))
map.remove(id);
}
}
}https://stackoverflow.com/questions/21268784
复制相似问题