我是 Java 新手。我只是在试验线程,我想创建一个类似线程池的东西(如果这实际上是我正在做的......)。
基本上我有一个while循环,它会触发线程,直到还有要执行的任务&&而最大并发线程不大于n。每个线程使用 java.util.concurrent.locks.ReentrantLock 来提供一个锁,围绕任务计数变量在每个线程中减少,线程计数变量在线程开始时增加并在线程结束前减少(代码闻?):
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String[] args) {
//overcome limitation of closure not being able to modify outer variable with arr.
final int[] runningThreads = {0};
final int[] taskcount = {10};
final Lock _mutex = new ReentrantLock(true);
int maxThreadQty = 3;
while ((taskcount[0] > 0) && (runningThreads[0] < maxThreadQty)) {
new Thread("T") {
public void run() {
System.out.println("New Thread Started");
_mutex.lock();
runningThreads[0]++;
System.out.println("Running Threads: " + runningThreads[0]);
System.out.println("Times to go: " + taskcount[0]);
_mutex.unlock();
// actually do something;
_mutex.lock();
taskcount[0]--;
runningThreads[0]--;
_mutex.unlock();
}
}.start();
}
}
}
当我运行代码时,新线程不断被触发,任务数只减少了两到三倍......
输出的最后几行(读取时间作为要执行的任务):
Running Threads: 565
Times to go: 8
Running Threads: 566
Times to go: 8
Running Threads: 567
Times to go: 8
Running Threads: 568
Times to go: 8
Running Threads: 569
Times to go: 8
Running Threads: 570
Times to go: 8
Running Threads: 571
Times to go: 8
Running Threads: 572
Times to go: 8
Running Threads: 573
Times to go: 8
Running Threads: 574
Times to go: 8
Running Threads: 575
Times to go: 8
CTRL-C
我确信我使用线程或锁的方式一定是完全错误的。但作为一个 java 新手,有很多东西我可能会错过(甚至可能是最基本的东西),一些帮助和一些让我回来在正确的道路上将不胜感激......!谢谢你。
我用它作为线程的参考:http: //tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
然后这个 stackoverflow 回答看看如何使用 ReentrantLock:https ://stackoverflow.com/a/12510490/988591
这是闭包无法修改外部变量的解决方法(使用数组值): http ://c2.com/cgi/wiki?ClosuresThatWorkAroundFinalLimitation