use*_*900 5 java compression multithreading
我仍然有一些麻烦缠绕线程,我试图以最简单的方式做到这一点.我知道线程都必须有一个从Runnable类继承的run方法,但是它们也可以有其他方法,对吗?
原因是,我有一个带有一些私有变量和run方法的线程.它调用它的run函数,一旦完成,我想用完全相同的run方法重用该线程.它完全相同,只是使用不同的变量.所以我可以添加类似setArray方法的东西(该线程包含一个私有字节数组),所以我只需用这个新数组再次调用run,或者是不允许的.我想简单地说,它就像是
Thread thread = new MyThread();
thread.start();
// Check if the thread has finished in a non-blocking way
if (thread.isAlive() == false) {
thread.setArray(newArray)
thread.start();
}
Run Code Online (Sandbox Code Playgroud)
基本上我只有一个固定数量的线程,当第一个线程完成运行时,我想稍微改变参数并让它再次运行.我不想让他们死,这似乎是连接所做的.
对于特定问题,我说4个线程,每个线程给出一个较大字节数组的设置大小块.每个线程使用Deflater压缩该数组,并将其结果传递给处理同步的管理器对象.一旦完成第一个线程(如获得数组第一部分的线程,而不是第一个完成的线程),它就会移动到未分配给线程的下一个块.
我知道线程池是一个选项,但它似乎有点矫枉过正,我真的不理解它们(我仍然遇到普通线程的问题).
Ste*_*n C 12
首先,最好使用标准Thread类(不要将其子类化!)并将应用程序代码放入实现的类中Runnable.这使得将应用程序逻辑与管理线程的问题分开更加容易.
其次,您必须了解Thread对象只调用run一次该方法.在之后run方法返回(或异常终止),Thread对象是死的,而不能起死回生.
So if you want to "reuse" Thread instances, you have to arrange that the run method is a loop that (somehow) waits for the next thing to be done. And before you know it you are implementing a thread pool.
There is another (more "modern") alternative to a thread pool. Create an ExecutorService instance, and use the submit() method to submit the Runnable instances for execution. The interface javadoc has a good usage example, using an executor service instance with a private thread pool. If you wanted to, you could reuse the Runnable instances, but generally it is simpler (and safer) to create new ones each time.