我想开发我的毕业设计项目,使多线程应用。我正在使用Hazelcast的免费版本,因此我无法寻求帮助。如何使用Hazelcast
我写了一个Java应用程序,单个计算机上工作。我正在使用LinkedList作为队列,并拥有一个包含5个工作线程的池。工作线程只是从队列中取出一个工作并执行它。
代码的工作:
package com.stackoverflow.multithread.app;
import java.util.Date;
/**
* Job
*/
public class Job implements Runnable {
private final Object req;
private final long createTime = new Date().getTime();
public Job(Object req) {
this.req = req;
}
public boolean isPoison() {
return req == null;
}
public long getWaitTime(){
return new Date().getTime() - createTime;
}
@Override
public void run() {
try {
//Do the job
} catch (Exception e){
e.printStackTrace();
}
}
}
代码工作队列
package com.stackoverflow.multithread.app;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* WorkQueue
*/
public class WorkQueue {
private static int minThreads;
private static int maxThreads;
private static final List<PoolWorker> threads = new ArrayList<PoolWorker>();
private static final LinkedList queue = new LinkedList();
private static WorkQueue instance = null;
/**
* WorkQueue
*/
protected WorkQueue() {
minThreads = 1;
maxThreads = 5;
for (int i = 0; i < minThreads; i++) {
PoolWorker worker = new PoolWorker();
threads.add(worker);
worker.start();
}
}
/**
* getInstance
*
* @return Singleton WorkQueue instance
*/
public static WorkQueue getInstance() {
if (instance == null) {
instance = new WorkQueue();
}
return instance;
}
/**
* clone
*
* @return null
* @throws CloneNotSupportedException: Singleton class can not be cloned.
*/
@Override
public WorkQueue clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Singleton class can not be cloned.");
}
public void execute(Job r) {
synchronized (queue) {
queue.addLast(r);
manageWorkers();
queue.notify();
}
}
private void manageWorkers(){
while ((queue.size()/2 > threads.size() || (queue.size() > 0 && ((Job)queue.peekFirst()).getWaitTime() > 1000)) && threads.size() < maxThreads){
PoolWorker worker = new PoolWorker();
threads.add(worker);
worker.start();
}
if (queue.size() < threads.size() && threads.size() > minThreads){
execute(new Job(null)); //poison
}
}
private class PoolWorker extends Thread {
@Override
public void run() {
Job r;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException ignored) {
}
}
r = (Job) queue.removeFirst();
manageWorkers();
if (r.isPoison()) {
break;
}
}
// If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (ExceptionInInitializerError e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
threads.remove(this);
}
}
}
现在我想打一个主动 - 主动模式这项工作,并希望使用HazelCast(V3 .3),确保每个和所有的作业应该只执行一次,即使其中一台计算机停机。
我检查的ExecutorService但它执行的工作一个接一个(单线程)。我找不到一个好的解决方案来做到这一点。人们提到ParallelExecutorService,但它不是在这个版本中可用,或者它不是免费版的一部分。
请注意,我没有做到这一点使用Hazelcast。我的任何免费解决方案都很好。
有什么建议吗?