现在的位置: 首页 > 综合 > 正文

Java Concurrency

2012年08月19日 ⁄ 综合 ⁄ 共 3262字 ⁄ 字号 评论关闭

ConcurrencyThe issue that can make a difference is blocking. If one task in your program is unable to continuebecause of some condition outside of the control of the program(typically I/O), we say that the taskor the thread blocks. Without concurrency, the whole program comes to a stop until the external condition changes. If the program is written using concurrency, however, the other tasks in the programcan toncinue to execute when one task is blocked, so the program continues to move forward.
A Runnable is a separate task that performs work, but it doesn't reurn a value. If you want the task to produce a value when it's done,

you can implement the Callable interface rather than the Runnable interface. Callable, introduced in Java SE5, is a generic with a type parameter representing the return value from the method call() (instead of run()), and must be invoked using an ExecutorService submit() method. Here's a simple example.

//LiftOff.java

package threaddemo;

public class LiftOff implements Runnable {

	protected int countDown=10;
	public LiftOff() {
	}
	public LiftOff(int countDown) {
		this.countDown=countDown;
	}
	
	private static int taskID=0;
	public int id=taskID++;

	public String status() {
		return "#" + id + " is at " + countDown;
	}
	
	@Override
	public void run() {
		while(countDown-->0){
			System.out.println(status());
			Thread.yield();
		}
	}

}
//TaskWithResult.java

package threaddemo;

import java.util.concurrent.Callable;

public class TaskWithResult implements Callable<String> {
	private static int cnt=0;
	private final int num=cnt++;
	private int i;
	
	public TaskWithResult() {
	}

	public TaskWithResult(int i) {
		this.i = i;
	}

	@Override
	public String call() throws Exception {
		return "My Thrad ID:"+num+"返回的字符串为:" + i;
	}
	
}

//Test.java

package threaddemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		
//		Thread thread=new Thread(new LiftOff());
//		thread.start();
//		System.out.println("Main End");		
		////////////////////////////////////////		
//		for (int i = 0; i < 5; i++) {
//			Thread thread = new Thread(new LiftOff());
//			thread.start();
//		}
//		System.out.println("Main End");
		
		///////////////////////////////////////////
		//ExecutorService svs = Executors.newCachedThreadPool();
//		ExecutorService svs = Executors.newFixedThreadPool(5);
//		for (int i = 0; i < 5; i++) {
//			Thread thread = new Thread(new LiftOff());
//			svs.execute(thread);			
//		}
//		svs.shutdown();
//
		/////////////////////////////////////////
		
		ExecutorService svs = Executors.newCachedThreadPool();
		List<Future<String>> result=new ArrayList<Future<String>>();
		for(int i=0;i<10;i++){
			result.add( svs.submit(new TaskWithResult(i)) );
			//Old-style:
			//Thread.sleep(100);
			//Java SE5/6-style:
			TimeUnit.MILLISECONDS.sleep(100);
		}
		for (Future<String> future : result) {
			try {
				System.out.println(future.get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			finally{
				svs.shutdown();
			}
		}
//		The submit() method produces a Future object, parameterized for 
//		the particular type of result returned by the Callable. You can query
//		the Future with isDone() to see if it has completed. When the task
//		is completed and has a result, you can call get() to fetch the result.
//		You can simply call get() without checking isDone(), in which case
//		get() will block until the result is ready. You can also call get()
//		with a timeout, or isDone() to see if the task has completed, before 
//		trying to call get() to fetch the result.
		
	}

}

抱歉!评论已关闭.