java 異步執行任務,返回進度

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;




/**
 * 
 * @author CaoZhongping
 *
 *異步任務處理
 */
public class AsyncTaskExecutor<V>{
	
	private Callable<V> callable;
    private int threadSize ; 
	private static ExecutorService service;
	
	public AsyncTaskExecutor(Callable<V> callable, int threadSize) {
		super();
		this.callable = callable;
		this.threadSize = threadSize;
	}

	/***
	 * 開始任務 返回進度
	 * @return
	 */
	public List<Future<V>> start()
	{
		service = Executors.newFixedThreadPool(threadSize);
		List<Future<V>> list = new ArrayList<Future<V>>(threadSize);
		for (int i = 0; i < threadSize; i++)
		{
			list.add(service.submit(callable));
		}
		return list;
	}

	public  ExecutorService getService() {
		return service;
	}
	
	
}
//GUI

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;


public class Client extends JFrame{

	private static final long serialVersionUID = 1L;
    private JTable table;
    private JLabel label;
    private JTextField field;
    private JButton button;
    private JTextArea status;
    private JProgressBar bar;
    private JLabel label2;
    public Client(int width, int height) {
    	table = new JTable(new DefaultTableModel());
    	label = new JLabel("名稱");
    	field = new JTextField(15);
    	button = new JButton("查找");
    	status = new JTextArea(10,5);
    	label2 = new JLabel("進度");
    	status.setForeground(Color.blue);
    	bar = new JProgressBar();
    	Box box = Box.createHorizontalBox();
    	box.add(Box.createHorizontalStrut(50));
    	box.add(label);
    	box.add(field);
    	box.add(button);
    	box.add(Box.createHorizontalStrut(50));
    	this.setLayout(new BorderLayout());
    	this.add(box,BorderLayout.NORTH);
    	this.add(table,BorderLayout.CENTER);
    	this.add(new JScrollPane(status),BorderLayout.SOUTH);
    	this.setSize(width, height);
    	this.button.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					long st = System.currentTimeMillis();
					AsyncTaskExecutor<Long> executor = new AsyncTaskExecutor<Long>(new MyTask(1000,status),5);
					long res=0;
					button.setEnabled(false);
					for(Future<Long> future:executor.start()){
						if(!future.isDone())
						{
							long temp =future.get().longValue();
							res+=temp;
						}
					}
					executor.getService().shutdown();
					status.append("\n執行完成:"+res+" 耗時:"+(System.currentTimeMillis()-st));
					button.setEnabled(true);
				}  catch (Exception e) {
					e.printStackTrace();
				}
				
			}});
	}
    public DefaultTableModel getModel()
    {
    	return (DefaultTableModel) this.table.getModel();
    }
	public static void main(String[] args) {
		Client client = new Client(300,400);
		client.setDefaultCloseOperation(Client.EXIT_ON_CLOSE);
		client.setLocationByPlatform(true);
		client.setVisible(true);
	}
	class MyTask implements Callable<Long>
	{
		private int size;
		private JTextArea area;
		

		public MyTask(int size, JTextArea area) {
			super();
			this.size = size;
			this.area = area;
		}


		@Override
		public Long call() throws Exception {
			long sum = 0; 
	        for (int i = 0; i <= size; i++) { 
	            sum += i; 
	            area.append("\n%"+sum);
	        }
	        return sum; 
	        
		}
		
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章