1.线程的实现方式:extends Thread 或者 implements Runnabletips:a. Thread implements Runnable 意味着构造函数Thread(Runnable target) 不光可以传入Runnable 接口的对象,还 可以传入一个Thread 类的对象,这样做完全可以将一个 Thread 对象中的run() 方法交由其他 的线程进行调用
b. 启动线程都是Thread.start();
2.在使用多线程技术时,代码的运行结果与代码执行顺序或调用顺序是无关的
/**
* Created by 38078 on 2017/11/5.
*/
public class Run {
public static void main(String[] args){
MyThread myThread = new MyThread();
myThread.start();
System.out.println("运行结束");
}
}
/**
* 运行结果:
* 运行结束
* MyThread
*/
tips:多次调用start() 方 法, 则 会 出 现 异 常Exception in thread "main" java.lang. IllegalThreadStateException
3.线程具有随机性,cpu执行哪个线程具有不确定性,执行start() 方法的顺序不代表线程启动的顺序。
4.当进行数据的共享时,需要注意线程安全问题
非线程安全主要是指多个线程对同一个对象中 的同一个实例变量进行操作时会出现值被更改、值不同步的情况,进而影响程序的执行流 程。
eg: i--;
1)取得原有 i 值。
2)计算 i-1。
3)对 i 进行赋值。
在这 3 个步骤中,如果有多个线程同时访问,那么一定会出现非线程安全问题。
解决方法:可以添加synchronized关键字进行加锁
4.线程的停止
在 Java 中有以下 3 种方法可以终止正在运行的线程:
1)使用退出标志,使线程正常退出,也就是当 run 方法完成后线程终止。
2)使用stop 方法强行终止线程,但是不推荐使用这个方法,因为stop 和 suspend 及 resume 一样,都是作废过期的方法,使用它们可能产生不可预料的结果。
3)使用 interrupt 方法中断线程。 但这个方法不会终止一个正在运行的线程,还需要加入一个判断才可以完成线 程的停止。
调用interrupt() 方法仅仅是在当前线程中打了一个停 止的标记,并不是真的停止线程。
判断线程是否时停止状态
1)this.interrupted():测试当前线程是否已经中断。当前线程是指运行 this.interrupted() 方法的线程。
2)this.isInterrupted():测试线程是否已经中断。
5.生产者消费者模型I(线程的通信)
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by 38078 on 2017/11/6.
* 生产者消费者模型(使用锁和条件进行同步)
*/
public class ConsumerProducer {
private static Buffer buffer = new Buffer();
public static void main(String[] args){
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new ProducerTask());
executorService.execute(new ConsumerTask());
executorService.shutdown();
}
private static class ProducerTask implements Runnable{
@Override
public void run(){
try {
int i=1;
while (true){
System.out.println("Producer write:" + i);
buffer.write(i++);
Thread.sleep((int)(Math.random()*10000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ConsumerTask implements Runnable{
@Override
public void run() {
try {
while (true){
System.out.println("Consumer reads:" + buffer.read());
Thread.sleep((int)(Math.random()*10000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class Buffer{
private static final int CAPACITY = 1;
private LinkedList<Integer> queue = new LinkedList<>();
private static Lock lock = new ReentrantLock();
private static Condition notEmpty = lock.newCondition();
private static Condition notFull = lock.newCondition();
public void write(int value){
lock.lock();
try {
while (queue.size() == CAPACITY){
System.out.println(" Wait For notFull Condition!");
notFull.await();
}
queue.offer(value);
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public int read(){
int value = 0;
lock.lock();
try{
while (queue.isEmpty()){
System.out.println(" Wait For notEmpty Condition!");
notEmpty.await();
}
value = queue.remove();
notFull.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
return value;
}
}
}
}
生产者消费者模型II
import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by 38078 on 2017/11/6.
* 生产者消费者模型II(使用阻塞队列,已实现同步)
*/
public class ConsumerProducer {
private static ArrayBlockingQueue<Integer> buffer = new ArrayBlockingQueue<Integer>(1);
public static void main(String[] args){
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new ProducerTask());
executorService.execute(new ConsumerTask());
executorService.shutdown();
}
private static class ProducerTask implements Runnable{
@Override
public void run(){
try {
int i=1;
while (true){
System.out.println("Producer write:" + i);
buffer.put(i++);
Thread.sleep((int)(Math.random()*10000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ConsumerTask implements Runnable{
@Override
public void run() {
try {
while (true){
System.out.println("Consumer reads:" + buffer.take());
Thread.sleep((int)(Math.random()*10000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
6.Fork/Join框架
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* Created by 38078 on 2017/11/6.
* Fork/Join框架(高效地自动执行和协调所有任务)开发并行程序:并行归并算法
*/
public class ParallelMergeSort {
public static void main(String[] args){
final int SIZE = 7000000;
int[] list1 = new int[SIZE];
int[] list2 = new int[SIZE];
for (int i=0; i<list1.length; i++){
list1[i] = list2[i] = (int)(Math.random()*10000000);
long startTime = System.currentTimeMillis();
parallelMergeSort(list1);
long endTime = System.currentTimeMillis();
System.out.println("可用的处理器个数:" + Runtime.getRuntime().availableProcessors() + " 并行归并排序整个过程花费了:" + (endTime-startTime));
startTime = System.currentTimeMillis();
MergeSort.mergeSort(list2);
endTime = System.currentTimeMillis();
System.out.println("归并排序整个过程花费了:" + (endTime-startTime));
}
}
/**
* @param list
* ForkJoinPool extends ExecutorService
* fork()安排一个任务的异步执行
* join当计算完成时返回任务的结果
* invoke()执行任务并且等待完成,并且返回计算结果
* invokeAll(ForkTask<T>... tasks) 分解所有任务,在任务都完成时返回
*/
public static void parallelMergeSort(int[] list){
RecursiveAction mainTask = new SortTask(list); //主任务(无返回值)
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(mainTask); //主任务放在ForkJoinPool中执行, invoke隐式的调用fork()执行任务,join()等待任务完成
}
private static class SortTask extends RecursiveAction{
private final int THRESHOLD = 500;
private int[] list;
SortTask(int[] list){
this.list = list;
}
/**
* compute()定义任务是怎么完成的
*
*/
@Override
protected void compute() {
if (list.length < THRESHOLD){
Arrays.sort(list); //内部实现:归并排序的变体
}else {
int[] firstHalf = new int[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length/2);
int[] secondHalf = new int[list.length-list.length/2];
System.arraycopy(list, list.length/2, secondHalf, 0, list.length-list.length/2);
invokeAll(new SortTask(firstHalf), new SortTask(secondHalf)); //调用invokeAll()
MergeSort.merge(firstHalf, secondHalf, list);
}
}
}
private static class MergeSort{
public static void mergeSort(int[] list){
if (list.length > 1){
int[] firstHalf = new int[list.length/2];
System.arraycopy(list, 0, firstHalf, 0, list.length/2);
mergeSort(firstHalf);
int[] secondHalf = new int[list.length-list.length/2];
System.arraycopy(list, list.length/2, secondHalf, 0, list.length-list.length/2);
mergeSort(secondHalf);
merge(firstHalf, secondHalf, list);
}
}
public static void merge(int[] list1, int[] list2, int[] temp){
int curIndexList1 = 0;
int curIndexList2 = 0;
int curIndexTemp = 0;
while (curIndexList1<list1.length && curIndexList2<list2.length){
if (list1[curIndexList1] < list2[curIndexList2]){
temp[curIndexTemp++] = list1[curIndexList1++];
}else {
temp[curIndexTemp++] = list2[curIndexList2++];
}
}
while (curIndexList1 < list1.length){
temp[curIndexTemp++] = list1[curIndexList1++];
}
while (curIndexList2 < list2.length){
temp[curIndexTemp++] = list2[curIndexList2++];
}
}
}
}
/**
可用的处理器个数:4 并行归并排序整个过程花费了:236
归并排序整个过程花费了:1212
可用的处理器个数:4 并行归并排序整个过程花费了:209
归并排序整个过程花费了:1218
可用的处理器个数:4 并行归并排序整个过程花费了:350
归并排序整个过程花费了:1153
*/
求最大值
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;
/**
* Created by 38078 on 2017/11/6.
* Fork/Join框架(高效地自动执行和协调所有任务)开发并行程序:求最大值
*/
public class ParallelMax {
public static void main(String[] args){
final int N = 9000000;
int[] list = new int[N];
for (int i=0; i<list.length; i++){
list[i] = i;
}
long startTime = System.currentTimeMillis();
System.out.println("最大值:" + max(list));
long endTime = System.currentTimeMillis();
System.out.println("可用的处理器个数:" + Runtime.getRuntime().availableProcessors() + " 整个过程花费了:" + (endTime-startTime));
}
public static int max(int[] list){
RecursiveTask<Integer> task = new MaxTask(list, 0, list.length); //RecursiveTask有返回值
ForkJoinPool pool = new ForkJoinPool();
return pool.invoke(task);
}
static class MaxTask extends RecursiveTask<Integer>{
private final static int THRESHOLD = 1000;
private int[] list;
private int low;
private int high;
public MaxTask(int[] list, int low, int high) {
this.list = list;
this.low = low;
this.high = high;
}
@Override
protected Integer compute() {
if (high-low < THRESHOLD){
int max = list[0];
for (int i=low; i<high; i++){
if (list[i] > max){
max = list[i];
}
}
return new Integer(max);
}else {
int mid = (low + high) / 2;
RecursiveTask<Integer> left = new MaxTask(list, low, mid);
RecursiveTask<Integer> right = new MaxTask(list, mid, high);
left.fork();
right.fork();
return new Integer(Math.max(left.join().intValue(), right.join().intValue()));
}
}
}
}
/**
* 最大值:8999999
* 可用的处理器个数:4 整个过程花费了:203
*/