gpt4 book ai didi

java - 并行四任务执行

转载 作者:行者123 更新时间:2023-11-29 04:19:59 25 4
gpt4 key购买 nike

我想使用四个线程独立执行四个任务。我想减少执行时间。但是这个程序不能减少执行时间。在这个程序中,顺序执行时间小于并行执行时间。我想从顺序执行中更快地执行程序。我怎样才能并行执行四个任务并减少执行时间。请删除此代码的问题并给出解决方案。

package TestParallel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
*
* @author Sohel Rana
*/
public class Executor {

public void encrypt(File fname) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); //using AES-256
SecretKey key = keyGen.generateKey(); //generating key
// System.out.println("Key = " + bytesToHex(key.getEncoded()));
Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES
aesCipher.init(Cipher.ENCRYPT_MODE, key); //initializing cipher for encryption with key

//creating file output stream to write to file
try (FileOutputStream fos = new FileOutputStream(fname + ".aes")) {
//creating object output stream to write objects to file
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key); //saving key to file for use during decryption

//creating file input stream to read contents for encryption
try (FileInputStream fis = new FileInputStream(fname)) {
//creating cipher output stream to write encrypted contents
try (CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)) {
int read;
byte buf[] = new byte[4096];
while ((read = fis.read(buf)) != -1) //reading from file
{
cos.write(buf, 0, read); //encrypting and writing to file
}
}
}
// fname.delete();
}

}

public static void main(final String[] args) throws InterruptedException {
final ExecutorService pool = Executors.newFixedThreadPool(4);

File file1 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\33 - Overflow Menu.mp4");
File file2 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\Java Cryptography Tutorials 1 AES Encryption and Decryption using Java.mp4");
File file3 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\30 - Dank Meme Bro.mp4");
File file4 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\How to change API level Android Studio.mp4");

Executor ex = new Executor();
long startTime = System.currentTimeMillis();
pool.execute(() -> {
try {
ex.encrypt(file1);
ex.encrypt(file2);
ex.encrypt(file3);
ex.encrypt(file4);
} catch (Exception ex1) {
Logger.getLogger(Executor.class.getName()).log(Level.SEVERE, null, ex1);
}
});

pool.shutdown();

if (!pool.awaitTermination(1, TimeUnit.DAYS)) {
System.err.println("Pool did not terminate.");
}
long endTime = System.currentTimeMillis();

System.out.println("Paralle took time " + (endTime - startTime)
+ " milliseconds.");

}
}

最佳答案

这是创建一个 Runnable,它一个接一个地运行各个 encrypt

    pool.execute(() -> {
try {
ex.encrypt(file1);
ex.encrypt(file2);
ex.encrypt(file3);
ex.encrypt(file4);
} catch (Exception ex1) {
Logger.getLogger(Executor.class.getName()).log(Level.SEVERE, null, ex1);
}
});

你需要做的是类似

for (File f : new File[] { file1, file2, file3, file4}) {
pool.execute(() -> {
try {
ex.encrypt(f);
} catch (Exception ex1) {
Logger.getLogger(Executor.class.getName()).log(Level.SEVERE, null, ex1);
}
});
}

附带说明一下,您等待线程完成的方式之所以有效,只是因为线程池的大小足以启动所有提交的任务。如果您要扩展此解决方案以添加更多文件,那么这些文件可能永远不会被编码,因为执行程序将它们放在队列中但尚未启动;这意味着它们根本不会启动,因为这是在 ExecutorService 上调用 shutdown 的效果之一。

关于java - 并行四任务执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49974455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com