1.Callable
通过Runnable接口定义的任务其run方法没有返回值。要想获得返回值,需要通过Callable接口来定义任务,其call方法可以有返回值。而且,Callable任务只能通过 ExecutorService.submit方法来调用。submit方法会返回Future类型的对象,可以通过isDone方法来检查任务是否完成,通过get方法来获取任务的返回值。当然也可以不调用isDone方法而直接调用get方法,这时get方法将阻塞直到任务完成得到返回值。
请看下面的实例:
package org.fan.learn.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by thinkpad on 2016/6/2.
*/
class TaskWithResult implements Callable {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
public String call() throws Exception {
return "result of Thread:#" + id ;
}
}
public class CallableDemo {
public static void main(String[] args) {
List<Future<String>> list = new ArrayList<Future<String>>();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
list.add(executorService.submit(new TaskWithResult(i)));
}
for (Future<String> future : list) {
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
System.out.println("main exit");
}
}
执行结果如下所示:
result of Thread:#0
result of Thread:#1
result of Thread:#2
result of Thread:#3
result of Thread:#4
main exit
2.sleep
在java 1.5之后,JDK提供了新的sleep作为TimeUnit的一部分。如下所示:
TimeUnit.MILLISECONDS.sleep(1000);表示休眠1000ms即1s。
Thread.sleep(1000); Thread.sleep的单位也是ms。
但是使用TimeUnit中的sleep可以很方便的看到休眠的时间单位。
3.yield
yield表示线程主动让出CPU让其他线程来执行。但是,这并不能保证将被采纳,也就是说其他线程不一定就会执行,也有可能还是这个线程执行。而且,调用yield也是在建议具有相同优先级的其他线程执行。
4.优先级
可以向调度器传递线程的优先级来向调度器说明线程的重要性。调度器倾向于让优先级高的线程来执行。当然,低优先级的线程也有机会来执行但是其执行频率稍微低了些而已。
可以通过Thread.currentThread()方法来获取当前线程的引用。调用System.out.println(Thread.currentThread)可以打印出当前线程的名字,优先级,线程组信息。
可以通过调用Thread.currentThread().getPriority()方法得到当前线程的优先级,通过调用setPriority()方法来设置优先级。注意:setPriority最好在run方法的开头,而不是在任务的构造方法中调用,因为此时执行器还没有执行任务。
如下所示(本例子只是为了说明设置优先级的方式):
package org.fan.learn.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by thinkpad on 2016/6/2.
*/
class PriorityTask implements Runnable {
private int priority;
public PriorityTask(int priority) {
this.priority = priority;
}
public void run() {
Thread.currentThread().setPriority(priority);
System.out.println(Thread.currentThread());
}
}
public class PriorityDemo {
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exe.execute(new PriorityTask(Thread.MIN_PRIORITY));
}
exe.execute(new PriorityTask(Thread.MAX_PRIORITY));
exe.shutdown();
}
}
执行结果如下所示:
Thread[pool-1-thread-3,1,main]
Thread[pool-1-thread-5,1,main]
Thread[pool-1-thread-4,1,main]
Thread[pool-1-thread-6,10,main]
Thread[pool-1-thread-1,1,main]
Thread[pool-1-thread-2,1,main]
上面的执行结果从中括号中可以看到线程的名字,优先级,线程组。
注意:
《Thinking in java》中,有这么一句话,绝大多数时间里,所有线程都应该以默认的优先级运行,试图操作线程优先级通常是一种错误。
向控制台打印是不能被中断的。
而且JDK中定义了10个优先级,但是它很难与操作系统的线程优先级有一一对应的关系,因此在设置线程优先级时,通常是设置三个常量:Thread.MIN_PRIORITY,Thread.NORM_PRIORITY,Thread.MAX_PRIORITY。