我正在尝试使用两个threadPoolExecutors应用某些数据的多线程生产者/消费者的原则,我注意到一切正常,但程序拒绝关闭,一些线程在关闭2个threadPools后仍在运行:
在主要班级:
public Form1()
{
InitializeComponent();
}
private byte[] StringToByteArray(string str)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetBytes(str);
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "Select document_content FROM[Document] WHERE documant_id= @id_doc";
comm.Connection = cn;
comm.Parameters.AddWithValue("@id_doc", 1241);
using (SqlDataReader oReader = comm.ExecuteReader())
{
while (oReader.Read())
{
downloadedDoc = oReader["document_content"].ToString();
}
}
cn.Close();
byte[] downloadedPDF = StringToByteArray(downloadedDoc);
File.WriteAllBytes(@"mypath", downloadedPDF);
}
在制作人类中:
ExecutorService executor = new ThreadPoolExecutor(10, 10, 40, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(edmsIds.size()));
ExecutorService consumerExecutor = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(edmsIds.size()));for(
String edmsID:edmsIds)
{
Runnable worker = new BatchWorkerThread(resumeFile, stratrKeysToUpdate, xslFiles, errorThrown, edmsID,
consumerExecutor, edmsIds.size(), executor);
executor.execute(worker);
}
答案 0 :(得分:3)
请参阅doc:
除了尽力尝试停止处理之外,还有无保证 积极执行任务。例如,典型的实现方式 通过Thread.interrupt()取消,因此任何无法响应的任务 中断可能永远不会终止。
如果正在运行的任务不可中断(不响应中断信号),它将继续执行。
答案 1 :(得分:1)
其实我想发布问题的原因和解决方案:
原因
我试图在没有终止的情况下关闭激励器。
解决方案
仅在使用简单代码终止后才将其关闭。
例如:
prodExecutor.shutdownNow();
while (!prodExecutor.isTerminated()) {}