常用方式
public static class Task implements Runnable {
@Override
public void run() {
System.out.println("执行任务。");
}
}
启动线程
public static void main(String[] args) throws ExecutionException, InterruptedException {
//实现Runnable
Thread thread = new Thread(new Task());
thread.start();
}
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("执行任务。");
}
}
启动线程
public static void main(String[] args) throws ExecutionException, InterruptedException {
//继承Thread
MyThread myThread = new MyThread();
myThread.start();
}
带返回值的接口,在java.util.concurrent.ExecutorService内运行。
public static class CallableTask implements Callable {
@Override
public Integer call() throws Exception {
//计算结果
return 0;
}
}
启动线程
public static void main(String[] args) throws ExecutionException, InterruptedException {
//实现Callable,配合线程池(executorService接口的submit)使用,具有返回值
CallableTask callableTask = new CallableTask();
ExecutorService executorService = new ThreadPoolExecutor(4, 8, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1 << 4));
Future integerFuture = executorService.submit(callableTask);
System.out.println(integerFuture.get());
executorService.shutdown();
}
现在不建议使用,建议用java.util.concurrent.ScheduledExecutorService代替。
//Timer,不建议使用了,无法控制,建议是用java.util.concurrent.ScheduledExecutorService代替
Timer timer = new Timer();
//10s后执行
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时任务");
}
}, 1000 * 10);
在java1.7添加的应该属于线程池范畴,写在这里了,fork,join,后面详细讲讲它的实现,它执行java.util.concurrent.ForkJoinTask
执行任务分类java.util.concurrent.RecursiveAction不带返回值的递归操作,java.util.concurrent.RecursiveTask带返回值的递归操作。
接下来我们用分别用单线程和ForkJoinPoll对数组排序,求斐波拉契数列第n位数是什么
private static void mergeSort() {
int[] array = randomArray(100, 100);
mergeSort(array, 0, array.length - 1);
printArray(array, "排序结果:");
}
private static void mergeSort(int[] array, int left, int right) {
if (left >= right) {
return;
}
int mid = left + ((right - left) >>> 1);
//左边排序
mergeSort(array, left, mid);
//右边排序
mergeSort(array, mid + 1, right);
//左后排序后合并
merge(array, left, mid, right);
}
private static void merge(int[] array, int left, int mid, int right) {
int[] helper = new int[right - left + 1];
int helperIndex = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
helper[helperIndex++] = array[l] < array[r] ? array[l++] : array[r++];
}
while (l <= mid) {
helper[helperIndex++] = array[l++];
}
while (r <= right) {
helper[helperIndex++] = array[r++];
}
System.arraycopy(helper, 0, array, left, helper.length);
}
//forkJoin多线程排序
forkJoinPool.invoke(new MyRecursiveAction(array, 0, array.length - 1));
printArray(array, "结果:");
/**
* 没有返回值的递归任务,排序
*/
public static class MyRecursiveAction extends RecursiveAction {
int[] array;
int left;
int right;
public MyRecursiveAction(int[] array, int left, int right) {
this.array = array;
this.left = left;
this.right = right;
}
@Override
protected void compute() {
if (left >= right) {
return;
}
int mid = left + ((right - left) >>> 1);
invokeAll(new MyRecursiveAction(array, left, mid), new MyRecursiveAction(array, mid + 1, right));
merge(array, left, mid, right);
}
private void merge(int[] array, int left, int mid, int right) {
int[] helper = new int[right - left + 1];
int helperIndex = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
helper[helperIndex++] = array[l] < array[r] ? array[l++] : array[r++];
}
while (l <= mid) {
helper[helperIndex++] = array[l++];
}
while (r <= right) {
helper[helperIndex++] = array[r++];
}
System.arraycopy(helper, 0, array, left, helper.length);
}
}
private static int fibonacci(int value) {
if (value == 1 || value == 2) {
return 1;
}
return fibonacci(value - 1) + fibonacci(value - 2);
}
//forkJoin多线程求斐波拉契数列第n个数
ForkJoinTask forkJoinTask= forkJoinPool.submit(new MyRecursiveTask(10));
System.out.println("结果"+forkJoinTask.get());
/**
* 带返回值递归任务,累加
*/
public static class MyRecursiveTask extends RecursiveTask {
private int value;
public MyRecursiveTask(int value) {
this.value = value;
}
@Override
protected Integer compute() {
if (value == 1 || value == 2) {
return 1;
}
MyRecursiveTask task1 = new MyRecursiveTask(value - 1);
task1.fork();
MyRecursiveTask task2 = new MyRecursiveTask(value - 2);
task2.fork();
return task1.join() + task2.join();
}
}
Java中线程启动就讲完了,下一讲,进程内线程间通信。
以下是完成代码:
/**
* @author baopz
*/
public class UsingThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//实现Runnable
Thread thread = new Thread(new Task());
thread.start();
//继承Thread
MyThread myThread = new MyThread();
myThread.start();
//实现Callable,配合线程池(executorService接口的submit)使用,具有返回值
CallableTask callableTask = new CallableTask();
ExecutorService executorService = new ThreadPoolExecutor(4, 8, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1 << 4));
Future integerFuture = executorService.submit(callableTask);
System.out.println(integerFuture.get());
executorService.shutdown();
//Timer,不建议使用了,无法控制,建议是用java.util.concurrent.ScheduledExecutorService代替
Timer timer = new Timer();
//10s后执行
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时任务");
}
}, 1000 * 10);
//1.7,先分开,后合并,归并
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
int[] array = randomArray(100, 100);
//单线程归并排序
mergeSort();
//forkJoin多线程排序
forkJoinPool.invoke(new MyRecursiveAction(array, 0, array.length - 1));
printArray(array, "结果:");
//单线程斐波拉契数列,第n个数是什么?1、1、2、3、5、8、13、21、34、55
System.out.println(fibonacci(10));
//forkJoin多线程求斐波拉契数列第n个数
ForkJoinTask forkJoinTask= forkJoinPool.submit(new MyRecursiveTask(10));
System.out.println("结果"+forkJoinTask.get());
}
private static int fibonacci(int value) {
if (value == 1 || value == 2) {
return 1;
}
return fibonacci(value - 1) + fibonacci(value - 2);
}
private static int[] randomArray(int size, int bound) {
int[] array = new int[100];
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(1000);
}
printArray(array, "随机数组:");
return array;
}
private static void printArray(int[] array, String prefix) {
if (prefix != null) {
System.out.println(prefix);
}
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
private static void mergeSort() {
int[] array = randomArray(100, 100);
mergeSort(array, 0, array.length - 1);
printArray(array, "排序结果:");
}
private static void mergeSort(int[] array, int left, int right) {
if (left >= right) {
return;
}
int mid = left + ((right - left) >>> 1);
//左边排序
mergeSort(array, left, mid);
//右边排序
mergeSort(array, mid + 1, right);
//左后排序后合并
merge(array, left, mid, right);
}
private static void merge(int[] array, int left, int mid, int right) {
int[] helper = new int[right - left + 1];
int helperIndex = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
helper[helperIndex++] = array[l] < array[r] ? array[l++] : array[r++];
}
while (l <= mid) {
helper[helperIndex++] = array[l++];
}
while (r <= right) {
helper[helperIndex++] = array[r++];
}
System.arraycopy(helper, 0, array, left, helper.length);
}
/**
* 带返回值递归任务,累加
*/
public static class MyRecursiveTask extends RecursiveTask {
private int value;
public MyRecursiveTask(int value) {
this.value = value;
}
@Override
protected Integer compute() {
if (value == 1 || value == 2) {
return 1;
}
MyRecursiveTask task1 = new MyRecursiveTask(value - 1);
task1.fork();
MyRecursiveTask task2 = new MyRecursiveTask(value - 2);
task2.fork();
return task1.join() + task2.join();
}
}
/**
* 没有返回值的递归任务,排序
*/
public static class MyRecursiveAction extends RecursiveAction {
int[] array;
int left;
int right;
public MyRecursiveAction(int[] array, int left, int right) {
this.array = array;
this.left = left;
this.right = right;
}
@Override
protected void compute() {
if (left >= right) {
return;
}
int mid = left + ((right - left) >>> 1);
invokeAll(new MyRecursiveAction(array, left, mid), new MyRecursiveAction(array, mid + 1, right));
merge(array, left, mid, right);
}
private void merge(int[] array, int left, int mid, int right) {
int[] helper = new int[right - left + 1];
int helperIndex = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
helper[helperIndex++] = array[l] < array[r] ? array[l++] : array[r++];
}
while (l <= mid) {
helper[helperIndex++] = array[l++];
}
while (r <= right) {
helper[helperIndex++] = array[r++];
}
System.arraycopy(helper, 0, array, left, helper.length);
}
}
public static class CallableTask implements Callable {
@Override
public Integer call() throws Exception {
return 0;
}
}
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("执行任务。");
}
}
public static class Task implements Runnable {
@Override
public void run() {
System.out.println("执行任务。");
}
}
}