Java定时扫描线程

public class Task{
      private int taskId;
      private String taskName;
      private char state;
      // get set
}

 

package com.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.task.manager.Task;

public class ThreadPool {
	private List list;
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}

	private LinkedBlockingQueue taskList = new LinkedBlockingQueue();
	
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
	ExecutorService threadPool = Executors.newFixedThreadPool(1);
	
	private Runnable workTask = new Runnable() {
		public void run() {
			while(!taskList.isEmpty()){
				Task task = getTask();
				System.out.println("获得任务:"+task.getTaskName());
				list.remove(task);
				task.setState('1');
				list.add(task);
			}
		}
	};

	public void excute(Runnable run){
		threadPool.execute(run);
	}
	public Task getTask() {
		if(taskList.isEmpty()){
			System.out.println("任务队列为空!");
		}
		try{
			return (Task)taskList.take();
		}catch(InterruptedException e){
			e.printStackTrace();
		}
		return null;
	}
	public void setTask(List l){
		if(l!=null&&l.size()>0){
			for(int i=0;i temp = getAllTaskByState('0');
				setTask(temp);
			}	
		},5,5,TimeUnit.SECONDS);
	}
	
	public void createTask(){
		scheduler.scheduleAtFixedRate(new Runnable(){
			public void run() {
				System.out.println("定时添加任务");
				Task t = new Task();
				int id = 0;
				synchronized(list){
					if(list!=null && list.size()>0){
						id = list.size()+1;
					}
					t.setTaskId(id);
					t.setState('0');
					t.setTaskName("任务"+id);
					list.add(t);
				}
			}	
		},4,4,TimeUnit.SECONDS);
	}
	public List getAllTaskByState(char state){
		List temp = new ArrayList();
		synchronized(list){
			for(int i = 0;i < list.size();i++){
				Task t = list.get(i);
				if(t.getState() == '0'){
					temp.add(t);
				}
			}
		}
		return temp;
	}
	
	public static void main(String[] args){
		List tempList = new ArrayList();
		for(int i=0;i<20;i++){
			Task tempTask = new Task();
			tempTask.setTaskId(i);
			tempTask.setTaskName("任务"+i);
			tempTask.setState('0');
			tempList.add(tempTask);
		}
		ThreadPool taskManager = new ThreadPool();
		taskManager.setList(tempList);
		taskManager.scheduleTask();
		taskManager.createTask();
	}
}

 

 

 本人对Java线程的研究不多,很想弄懂线程相关知识,下面是本人的一个例子,还望大家指导如何学习好线程,如若有牛人提供资料,本人表示感谢

还望大家指正

你可能感兴趣的:(java线程)