我有一个回调函数,我在其中接收一个字符串。 该字符串将被传递到单独的线程进行处理,因为处理需要时间。 另外,由于多个回调可以同时发生,我希望有一个同步锁,直到我将字符串传递到新线程中。但我不希望新线程(正在进行处理的线程)也被锁定。
有人可以帮我弄清楚这个设计吗?
我编写了以下代码,但在这个代码中,我认为在单独线程的整个处理完成之前无法收到回调,从而违背了这个新线程的全部目的。
String sLine;
onClick(String line){
synchronized (lock) {
sLine = line;
new Thread(new Runnable() {
@Override
public void run() {
doProcessing(Sline);
}).start();
}
}
最佳答案
Also, since multiple callbacks can come simultaneously, I would like to have a synchronized lock till i pass the string into the new thread.
A:我认为你不需要在这里加锁。该字符串不能被多线程访问。
But I do not wish to have the new thread (where processing is going on) to be locked also.
A:我发现这里没有任何东西被锁定:)我认为如果你这样做会更好:
- 创建一个类Runner实现Runnable,这个类会做处理
- 每次收到回调时,都使用 ThreadPoolExecutor 来执行此 Runner。这可以帮助您重用 Thread 实例。
- 注意:这行代码不需要同步,如果需要,可以将同步放在处理方法中。
// Implement class Runner
public class Runner implements Runnable {
private String mLine;
public Runner(String line) {
mLine = line;
}
@Override
public void run() {
process();
}
public void process() {
// Do processing with mLine
// Put synchronized if you need, it bases on your context
}
}
// Initialize thread pool
private ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 1000, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
// Execute runner when receiving callback
onClick(String s) {
Runner runner = new Runner(s);
executor.execute(runner);
}
关于java - 同步锁和单独的线程: Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15925677/