将最近学习的JAVA多线程知识在这里进行总结和分享,以便以后查看。所有内容仅供参看,有不正确的地方欢迎指出。
一.基本概念
1.常见术语
- 多线程:指的是这个程序(一个进程)运行时产生了不止一个线程
- 并行:多个cpu实例或者多台机器同时执行一段处理逻辑
- 并发:通过cpu调度算法,不断切换时间片,执行线程.当一个线程处在运行状态时,其它线程处于挂起状态
- 线程安全:在并发情况下,一段逻辑经过多线程使用,线程的调度顺序不影响最终结果。
- 同步:使线程共享的资源始终保持一致和准确。
2.线程运行状态
- yield()方法:当前线程调用此方法,告诉cpu吧运行机会交给线程池中拥有相同优先级的线程。不保证一定能达到让位的目的,让步的线程可能再次被调度程度选中。yield()不会导致阻塞。
- join()方法:当前线程里调用其它线程的join方法,当前线程阻塞,但不释放对象锁,直到线程执行完毕或者到达设定的时间。
二.创建线程的四种方式
1.实现Runable接口实现run()方法
public class MyThread extends OtherClass implements Runnable {
public void run() {
System.out.println("MyThread.run()");
}
}
2.继承Thread类重写run方法。本质上是实现了 Runnable 接口的一个实例,通过 Thread类的 start() 实例方法。
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread.run()");
}
}
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();
3.实现Callable 接口实现call()抽象方法,通过 FutureTask 包装器创建带返回值的线程(底层是实现了runnable接口和future接口)
public class Test implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Test callableDemo=new Test();
FutureTask<Integer> result = new FutureTask(callableDemo);
new Thread(result).start();
System.out.println(result.get());
}
@Override
public String call() throws Exception {
int a=1;
int b=2;
System.out.println(a+b);
return "执行结果:"+(a+b);
}
}
4.线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。
public class Test implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//newFixedThreadPool创建固定大小的线程池
ExecutorService executorService= Executors.newFixedThreadPool(1);
Test callableDemo=new Test();
Future<String> future=executorService.submit(callableDemo);
System.out.println(future.get());
//关闭线程池
executorService.shutdown();
}
@Override
public String call() throws Exception {
int a=1;
int b=2;
System.out.println(a+b);
return "执行结果:"+(a+b);
}
}