我正在尝试编写一个Utility类,它有助于在单独的线程上执行任务,提供在任务启动之前执行某些操作的功能,以及在任务结束后执行某些操作的功能。
类似于Android的 AsyncTask
这是一堂课。
class MySync
{
public void preExecute() {}
public void executeInBackground() {}
public void postExecute() {}
public final void execute()
{
threadExecute.start();
}
private final Thread threadExecute = new Thread()
{
@Override
public void run()
{
try
{
MySync.this.preExecute();
MySync.this.executeInBackground();
MySync.this.postExecute();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
}
这是应该如何使用这个类的。该类的使用者将根据要求覆盖这些方法。
class RegisterStudent extends MySync
{
@Override
public void preExecute()
{
System.out.println("Validating Student details. Please wait...");
try
{
Thread.sleep(2000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
@Override
public void executeInBackground()
{
System.out.println("Storing student details into Database on Server. Please wait...");
try
{
Thread.sleep(4000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
@Override
public void postExecute()
{
System.out.println("Student details saved Successfully.");
}
}
最后开始任务:
public class AsyncDemo
{
public static void main(String... args)
{
new RegisterStudent().execute();
}
}
似乎工作正常。我的问题是,这是实现标题中提到的目标的正确方法吗?关于如何实现这一目标的任何建议?
答案 0 :(得分:1)
这有什么不好之处在于你强迫用户扩展你的课程。在java中,您只能扩展1个类。所以一个框架不应该把它拿走。
而是使用界面:
public interface AsyncTask {
public default void preExecute() {}
public default void executeInBackground() {}
public default void postExecute() {}
}
让用户将其传递给您的实用程序类:
class MySync
{
private AsyncTask task;
public MySync(AsyncTask task) {
this.task = task;
}
public final void execute()
{
threadExecute.start();
}
private final Thread threadExecute = new Thread()
{
@Override
public void run()
{
try
{
MySync.this.task.preExecute();
MySync.this.task.executeInBackground();
MySync.this.task.postExecute();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
}
答案 1 :(得分:1)
我不喜欢你的方法是你每次创建一个MySync
的新实例时创建一个新的线程,如果你打算创建你的对象的很多实例,那么这个实例是不可扩展的而且创建一个Thread是很昂贵的,如果我是你,我会使用一个执行器来限制分配的异步执行任务的线程总数,如果你只想使用一个线程,你可以这样做:
ExecutorService executor = Executors.newFixedThreadPool(1);
我也会为这样的事情重写你的代码:
public abstract class MySync implements Runnable {
@Override
public final void run() {
try {
preExecute();
executeInBackground();
} finally {
postExecute();
}
}
protected abstract void preExecute();
protected abstract void executeInBackground();
protected abstract void postExecute();
}
这样就可以为所有实现定义整个逻辑。
然后你可以像这样提交你的任务:
executor.submit(new RegisterStudent());
答案 2 :(得分:0)