java多线程程序设计二、线程返回值,优先级以及暂停的问题

1、待返回值的任务的建立需要实现的是Callable接口,实现其call方法,而且这个任务只能通过ExecutorService 的submit方法进行调用,且返回值是一个Future对象,下面看一个例子:
package multiThread;

import java.util.concurrent.Callable;
//带返回值的任务

public class TaskWithResult implements Callable<String> {
	private  int id;
	public TaskWithResult(int id){
		this.id=id;
	}
	
	public String call(){
		return "TaskWithResult "+id;
	}

}


//test

		ExecutorService exec=Executors.newCachedThreadPool();
		ArrayList<Future<String>> results=new ArrayList<Future<String>>();
		for(int i=0;i<10;++i){
			results.add(exec.submit(new TaskWithResult(i)));
		}
		for (Future<String> future : results) {
			try {
				System.out.println(future.get());
			} catch (InterruptedException ie) {
				System.out.println(ie.getMessage());
			}finally{
				exec.shutdown();
			}
		}

结果如下:
java多线程程序设计二、线程返回值,优先级以及暂停的问题
2、我们可以调用sleep方法让线程休眠一会例如:

public void run(){
		while(countDown-->0){
			System.out.println(status());
			//Thread.yield();
			try {
				TimeUnit.MILLISECONDS.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}



注意:在此处发生的异常不能够通过跨越线程传达到main方法中,所以我们需要在这里进行必要的捕获和处理。

3、线程的优先级
优先级的设置一般会在run函数里面进行
例如:

package multiThread;

public class SimplePriorities implements Runnable {
	private int countDown=5;
	private volatile double d;//no optimization
	private int priority;
	public SimplePriorities(int priority){
		this.priority=priority;
	}
	public String toString(){
		return Thread.currentThread()+": "+countDown;
	}
	
	public void run(){
		Thread.currentThread().setPriority(priority);
		
		while(true){
			for(int i=1;i<10000;++i){
				d+=(Math.PI+Math.E)/(double)i;
						if(i%1000==0)
							Thread.yield();//suggest other threads to run
			}
			System.out.println(this);
			if(--countDown==0)return;
		}
	}

}
                ExecutorService executorService=Executors.newCachedThreadPool();
		for(int i=0;i<5;++i){
			executorService.execute(new SimplePriorities(Thread.MIN_PRIORITY));
		}
		executorService.execute(new SimplePriorities(Thread.MAX_PRIORITY));
		executorService.shutdown();




你可能感兴趣的:(java多线程程序设计二、线程返回值,优先级以及暂停的问题)