我正在研究 Java 多线程,在为 4 个不同的文件分配给它们之后启动 4 个线程,以便将其上传到服务器。
我的目标是,当一个线程完成文件上传时,我需要启动另一个线程为其分配一个新文件。
每次文件上传后,我都会收到来自服务器的通知。
//添加第一组文件的代码
for (int count = 0; count < 4; count++) {
if (it.hasNext()) {
File current = new File((String) it.next());
try {
Thread t = new Thread(this, current );
t.start();
t.sleep(100);
} catch (Exception e) {
}
}
}
现在,我正在为另一个线程分配一个文件并使该线程保持等待状态。 当前一个线程通知时,当前线程应该开始上传。
if (tempThreadCounter == 4 ) {
if (it.hasNext()) {
File current = new File((String) it.next());
try {
Thread t = new Thread(this, current);
t.start();
synchronized (this) {
t.wait();
}
tempThreadCounter++;
} catch (Exception e) {
}
}
}
在 run 方法的最后一个语句中,我添加了以下语句。
public void run (){
// Performing different operations
//Final statement of the run method below
synchronized (this) {
this.notifyAll();
}
}
目前,5个线程全部同时开始上传。 应该是前 4 个线程应该开始上传,第五个线程只有在任何线程通知它已完成其操作时才应启动。
关于不正确的线程实现的任何建议。
最佳答案
您可以使用ExecutorService与 newFixedThreadPool并指定并发数为 1。但实际上,为什么需要多个线程呢?一个线程完成所有上传,以便用户界面保持响应应该就足够了。
ExecutorService exec = Executors.newFixedThreadPool(1); //1 thread at a time
for (int count = 0; count < 4; count++) {
if (it.hasNext()) {
File current = new File((String) it.next());
exec.execute(new Runnable() {
@Override
public void run() {
upload(current);
}
});
}
}
exec.shutdown();
exec.awaitTermination(900, TimeUnit.SECONDS);
关于java - 等待通知实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047993/