一、Thread调度的概述
import java.util.*; import java.text.*; public class Task implements Runnable { long n; String id; private long fib(long n) { if (n == 0) return 0L; if (n == 1) return 1L; return fib(n - 1) + fib(n - 2); } public Task(long n, String id) { this.n = n; this.id = id; } public void run() { Date d = new Date(); DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS"); long startTime = System.currentTimeMillis(); d.setTime(startTime); System.out.println("Starting task " + id + " at " + df.format(d)); fib(n); long endTime = System.currentTimeMillis(); d.setTime(endTime); System.out.println("Ending task " + id + " at " + df.format(d) + " after " + (endTime - startTime) + " milliseconds"); } }
import javathreads.examples.ch09.*; import javathreads.examples.ch09.*; public class ThreadTest { public static void main(String[] args) { int nThreads = 3; long n = 20; Thread t[] = new Thread[nThreads]; for (int i = 0; i < t. length; i++) { t[i] = new Thread( new Task(n, "Task " + i)); t[i].start(); } for (int i = 0; i < t. length; i++) { try { t[i].join(); } catch (InterruptedException ie) {} } } }
Starting task Task 1 at 07:06:24:443 Starting task Task 0 at 07:06:24:443 Starting task Task 2 at 07:06:24:443 Ending task Task 2 at 07:06:24:446 after 3 milliseconds Ending task Task 0 at 07:06:24:446 after 3 milliseconds Ending task Task 1 at 07:06:24:446 after 3 milliseconds
二、以Thread优先级来调度
更改线程的优先级。
首先调用线程的 checkAccess 方法,且不带不论什么參数。这可能抛出 SecurityException。
在其它情况下,线程优先级被设定为指定的 newPriority 和该线程的线程组的最大同意优先级相比較小的一个。
public final int getPriority()
返回线程的优先级。
返回:该线程的优先级。