Java 考虑到一个包含任务(task1、task2、task3、task1、task2、task3,…)的队列,如何通过恰好使用2个线程来执行队列中的任务
案例: 考虑到您有一个包含任务的队列(task1、task2、task3、task1、task2、task3等), 我如何使用2个线程来执行队列中的任务。 要求:Java 考虑到一个包含任务(task1、task2、task3、task1、task2、task3,…)的队列,如何通过恰好使用2个线程来执行队列中的任务,java,multithreading,Java,Multithreading,案例: 考虑到您有一个包含任务的队列(task1、task2、task3、task1、task2、task3等), 我如何使用2个线程来执行队列中的任务。 要求: 1.一个线程应该执行task1和task2,anthoner应该执行task3,或者相反 因为一些有限的条件,例如有限的外部资源 2.task3应始终在完成后执行,以执行task1和task2 按照队列的正确顺序 3应考虑差异情况,例如TASK1、TASK2的耗时。 任务3可能完全不同 4.不应该出死圈 代码 publ
- 1.一个线程应该执行task1和task2,anthoner应该执行task3,或者相反 因为一些有限的条件,例如有限的外部资源
- 2.task3应始终在完成后执行,以执行task1和task2 按照队列的正确顺序
- 4.不应该出死圈
3应考虑差异情况,例如TASK1、TASK2的耗时。 任务3可能完全不同
public class testRunManager {
public static void main(String[] args){
ConcurrentLinkedQueue<BaseTask> tasks = new ConcurrentLinkedQueue<>();
for (int index = 0; index < 10; index++) {
tasks.add(new Task1());
tasks.add(new Task2());
tasks.add(new Task3());
}
BaseRunManager.getInstance().addTasks(tasks);
Thread thread1 = BaseRunManager.getInstance().getNewThread(TaskThread.Type.BeforeWards);
Thread thread2 = BaseRunManager.getInstance().getNewThread(TaskThread.Type.AfterWards);
//start
thread1.start();
thread2.start();
}
}
public class TaskThread extends Thread{
enum Type{
BeforeWards,
AfterWards
}
Type type;
public TaskThread(Type type,Runnable runnable){
super(runnable);
this.type = type;
}
}
public interface ShouldRunBeforeWardsJob {
}
public interface ShouldRunAfterWardsJob {
}
abstract public class RunController {
public enum Performance {
BUSYING,
RUNNING,
PAUSED,
}
protected enum ControlState {
PAUSING,
PAUSED,
STOPING,
RESUMING,
RUNNING,
STEPPING,
}
private ControlState state = ControlState.RUNNING;
private Performance performance = Performance.BUSYING;
private List<ControlListener> listeners = new ArrayList<>();
protected ReentrantLock controlLock = new ReentrantLock();
protected Condition controlCondition = controlLock.newCondition();
public Performance getPerformance() {
return performance;
}
protected ControlState getState() {
return state;
}
public void addListener(ControlListener listener) {
listeners.add(listener);
}
public void removeListener(ControlListener listener) {
listeners.remove(listener);
}
public void pause() {
if (performance != Performance.RUNNING) {
return;
}
setState(ControlState.PAUSING);
}
public void step() {
if (performance != Performance.PAUSED) {
return;
}
setState(ControlState.STEPPING);
}
public void stop() {
if (performance != Performance.RUNNING && performance != Performance.PAUSED) {
return;
}
setState(ControlState.STOPING);
}
public void resume() {
if (performance != Performance.PAUSED) {
return;
}
setState(ControlState.RESUMING);
}
private void setPerformance(Performance p) {
if (performance != p) {
Performance old = this.performance;
this.performance = p;
for (ControlListener cl : listeners) {
cl.performChanged(old, p);
}
}
}
protected void setState(ControlState state) {
controlLock.lock();
try {
this.state = state;
switch (this.state) {
case RESUMING:
case STEPPING:
case PAUSING:
case STOPING:
controlCondition.signal();
setPerformance(Performance.BUSYING);
break;
case PAUSED:
setPerformance(Performance.PAUSED);
break;
case RUNNING:
setPerformance(Performance.RUNNING);
}
}finally {
controlLock.unlock();
}
}
public interface ControlListener {
void performChanged(Performance oldState, Performance newState);
}
}
public abstract class BaseTask {
enum State{
FINISH,
NOT
}
protected State state;
public State getState(){
return state;
}
public void setState(State state){
this.state = state;
}
abstract void runJob();
abstract void doJob();
}
public class BaseRunManager {
private static BaseRunManager instance;
private ConcurrentLinkedQueue<BaseTask> tasks = new
ConcurrentLinkedQueue<>();
public synchronized static BaseRunManager getInstance(){
if(instance == null){
instance = new BaseRunManager();
}
return instance;
}
public BaseRunManager(){
}
public void addTasks(ConcurrentLinkedQueue<BaseTask> tasks){
this.tasks = tasks;
}
public Thread getNewThread(TaskThread.Type type){
return new TaskThread(type,new BaseRunnable());
}
private class BaseRunnable extends RunController implements Runnable{
private BaseTask curTask;
private final AtomicBoolean afterwardsFinish = new AtomicBoolean(true);
private final AtomicInteger beforewardsFinishNum = new AtomicInteger(0);
private final AtomicInteger currentThreadNum = new AtomicInteger(0);
private final Condition condition = controlLock.newCondition();
@Override
public void run() {
currentThreadNum.incrementAndGet();
TaskThread curThread = (TaskThread)Thread.currentThread();
while (tasks.size()>0) {
//get task
controlLock.lock();
try {
curTask = tasks.peek();
if ((curTask instanceof ShouldRunBeforeWardsJob && curThread.type == TaskThread.Type.BeforeWards)
|| (curTask instanceof ShouldRunAfterWardsJob && curThread.type == TaskThread.Type.AfterWards)) {
tasks.poll();
if (curTask instanceof ShouldRunBeforeWardsJob) {
curTask.runJob();
beforewardsFinishNum.incrementAndGet();
condition.signalAll();
} else if (curTask instanceof ShouldRunAfterWardsJob) {
if (beforewardsFinishNum.get() / 2 != 0) {
condition.await();
curTask.runJob();
}
}
} else {
condition.awaitNanos(20);
continue;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
controlLock.unlock();
}
}
}
}
}
公共类testRunManager{
公共静态void main(字符串[]args){
ConcurrentLinkedQueue任务=新建ConcurrentLinkedQueue();
对于(int-index=0;index<10;index++){
添加(新任务1());
tasks.add(newtask2());
添加(新任务3());
}
BaserRunManager.getInstance().addTasks(任务);
Thread thread1=BaseRunManager.getInstance().getNewThread(tasksThread.Type.BeforeWards);
Thread thread2=BaseRunManager.getInstance().getNewThread(TaskThread.Type.after);
//开始
thread1.start();
thread2.start();
}
}
公共类TaskThread扩展线程{
枚举类型{
在此之前,
之后
}
类型;
公共任务线程(类型,可运行,可运行){
超级(可运行);
this.type=type;
}
}
公共接口应在作业之前运行{
}
公共接口应在之后运行作业{
}
抽象公共类RunController{
公共枚举性能{
忙碌,
跑步
停顿,
}
受保护的枚举控制状态{
停顿,
停顿,
回采,
恢复,,
跑步
踏步,
}
私有ControlState状态=ControlState.RUNNING;
私人绩效=绩效。忙碌;
私有列表侦听器=新的ArrayList();
受保护的ReentrantLock controlLock=新的ReentrantLock();
受保护条件controlCondition=controlLock.newCondition();
公共绩效{
回报绩效;
}
受保护的ControlState getState(){
返回状态;
}
公共void addListener(ControlListener侦听器){
添加(侦听器);
}
公共void removeListener(ControlListener侦听器){
删除(侦听器);
}
公共空间暂停(){
if(性能!=性能.正在运行){
返回;
}
设置状态(控制状态暂停);
}
公共无效步骤(){
如果(性能!=性能。暂停){
返回;
}
设置状态(ControlState.STEPPING);
}
公共停车场(){
if(performance!=performance.RUNNING&&performance!=performance.PAUSED){
返回;
}
设置状态(控制状态、停止);
}
公众简历(){
如果(性能!=性能。暂停){
返回;
}
设置状态(控制状态。恢复);
}
专用性能(性能p){
如果(性能!=p){
性能旧=此性能;
这个。性能=p;
for(ControlListener cl:侦听器){
cl.performChanged(旧版,p);
}
}
}
受保护的无效设置状态(控制状态){
controlLock.lock();
试一试{
this.state=状态;
开关(此状态){
案件恢复审理:
案例步骤:
案例暂停:
案例回采:
controlCondition.signal();
设置性能(性能、忙碌);
打破
案例暂停:
setPerformance(Performance.PAUSED);
打破
案件审理:
设置性能(Performance.RUNNING);
}
}最后{
controlLock.unlock();
}
}
公共接口控制器{
无效性能更改(性能旧状态、性能新状态);
}
}
公共抽象类基任务{
枚举状态{
完成,
不
}
受保护国家;
公共状态getState(){
返回状态;
}
公共无效设置状态(状态){
this.state=状态;
}
抽象void runJob();
抽象void doJob();
}
公共类BaserRunManager{
私有静态BaserRunManager实例;
私有ConcurrentLinkedQueue任务=新建
ConcurrentLinkedQueue();
公共同步静态BaserRunManager getInstance(){
if(实例==null){
instance=new BaseRunManager();
}
返回实例;
}
公共BaserRunManager(){
}
公共void addTasks(ConcurrentLinkedQueue任务){
这个。任务=任务;
}
公共线程getNewThread(TaskThread.Type){
返回新的TaskThread(类型,new BaseRunnable());
}
私有类BaseRunnable扩展RunController实现Runnable{
私人基地任务;
private final AtomicBoolean afterwardsFinish=新的AtomicBoolean(真);
private final AtomicInteger beforewardsFinishNum=新的AtomicInteger(0);
私有最终AtomicInteger currentThreadNum=新的AtomicInteger(0);
私有最终条件Condition=controlLock.newCondition();
public interface SerializedRunnable extends Runnable {
int getKey();
}
public void execute(Runnable command) {
final int key;
if (command instanceof SerializedRunnable ) {
key = ((SerializedRunnable ) command).getKey();
}
final int index =Math.abs(key) % size;
workers[index].execute(command);
public static void main(String[] args) {
final BlockingQueue<BaseTask> tasks = new LinkedBlockingQueue<>();
final BlockingQueue<BaseTask> queue2 = new LinkedBlockingQueue<>();
for (int index = 0; index < 10; index++) {
tasks.add(new BaseTask("Task1"));
tasks.add(new BaseTask("Task2"));
tasks.add(new BaseTask("Task3"));
}
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
BaseTask task = tasks.take();
task.run();
task = tasks.take();
task.run();
task = tasks.take();
queue2.offer(task);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
BaseTask task = queue2.take();
task.run();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
thread2.start();
thread1.start();
}
private static class BaseTask implements Runnable {
private final String name;
public BaseTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + " ["
+ Thread.currentThread().getName() + "]");
}
}