1、程序、进程、线程
程序:是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
进程(Process):是执行程序的一次执行过程,是一个动态的概念,是系统资源分配的单位。
线程(Thread):通常在一个进程中可以包含若干个线程,一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位。
很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
2、线程的创建
方式一:(1)自定义线程类继承Thread类;(2)重写run()方法,编写线程执行体;(3)创建线程对象,调用start()方法启动线程
- 1 public class StartThread extends Thread{ //1、自定义线程类继承Thread类
- 2 @Override //2、重写run()方法,编写线程执行体
- 3 public void run() {
- 4 for (int i = 0; i < 100; i++) {
- 5 System.out.println("run"+i);
- 6 }
- 7 }
- 8
- 9 public static void main(String[] args) {
- 10 StartThread startThread = new StartThread();
- 11 startThread.start(); //3、创建线程对象,调用start()方法启动线程
- 12 for (int i = 0; i < 500; i++) {
- 13 System.out.println("main"+i);
- 14 }
- 15 }
- 16 }

线程不一定立即执行,由CPU安排调度
方式二:(1)自定义线程类实现Runnable接口;(2)实现run()方法,编写线程执行体;(3)创建线程对象,调用start()方法启动线程
- 1 public class MyRunnable implements Runnable{ //1、自定义线程类实现Runnable接口
- 2 @Override //2、重写run()方法,编写线程执行体
- 3 public void run() {
- 4 for (int i = 0; i < 100; i++) {
- 5 System.out.println("run"+i);
- 6 }
- 7 }
- 8
- 9 public static void main(String[] args) {
- 10 MyRunnable myRunnable = new MyRunnable();
- 11 //3、创建线程对象,调用start()方法启动线程,代理
- 12 new Thread(myRunnable).start();
- 13
- 14 for (int i = 0; i < 500; i++) {
- 15 System.out.println("main"+i);
- 16 }
- 17 }
- 18 }

推荐使用实现Runnable接口,避免单继承局限性。
方式三:(1)实现Callable接口,需要返回值类型;(2)重写call方法,需要抛出异常;(3)创建目标对象;(4)创建执行服务:ExecutorService s = Executors.newFixedThreadPool(1);
(5)提交执行:Future
- 1 public class MyCallable implements Callable
{ //1、实现Callable接口,需要返回值类型 - 2 @Override //2、重写call方法,需要抛出异常;
- 3 public Boolean call() throws Exception {
- 4 for (int i = 0; i < 100; i++) {
- 5 System.out.println(Thread.currentThread().getName()+":"+i); //获取当前线程名字
- 6 }
- 7 return true;
- 8 }
- 9
- 10 public static void main(String[] args) {
- 11 //3、创建目标对象;
- 12 MyCallable m1 = new MyCallable();
- 13 MyCallable m2 = new MyCallable();
- 14 MyCallable m3 = new MyCallable();
- 15 //4、创建执行服务:
- 16 ExecutorService s = Executors.newFixedThreadPool(3);
- 17 //5、提交执行:
- 18 Future
r1 = s.submit(m1); - 19 Future
r2 = s.submit(m2); - 20 Future
r3 = s.submit(m3); - 21 //6、获取结果:
- 22 try {
- 23 boolean rs1 = r1.get();
- 24 boolean rs2 = r2.get();
- 25 boolean rs3 = r3.get();
- 26 } catch (InterruptedException | ExecutionException e) {
- 27 throw new RuntimeException(e);
- 28 }
- 29 //7关闭服务:
- 30 s.shutdownNow();
- 31 }
- 32 }
3、Lambda表达式 (JDK8)
(params) -> expression[表达式]
(params) -> statement[语句]
(params) -> {statements}
函数式接口:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。对于函数式接口,我们可以通过lambda表达式来创建该接口的对象。
- 1 public class TestLambda {
- 2 //静态内部类
- 3 static class Like2 implements ILike{
- 4 @Override
- 5 public void like() {
- 6 System.out.println("I like lambda2");
- 7 }
- 8 }
- 9 public static void main(String[] args) {
- 10 //局部内部类
- 11 class Like3 implements ILike{
- 12 @Override
- 13 public void like() {
- 14 System.out.println("I like lambda3");
- 15 }
- 16 }
- 17
- 18 ILike like = new Like1();
- 19 like.like();
- 20 like = new Like2();
- 21 like.like();
- 22 like = new Like3();
- 23 like.like();
- 24 //匿名内部类
- 25 like = new ILike() {
- 26 @Override
- 27 public void like() {
- 28 System.out.println("I like lambda4");
- 29 }
- 30 };
- 31 like.like();
- 32 //lambda表达式
- 33 //(1)
- 34 like = () -> {
- 35 System.out.println("I like lambda5");
- 36 };
- 37 like.like();
- 38 //(2)花括号简化,只允许有一行代码,多行必须要用代码块
- 39 like = () -> System.out.println("I like lambda6");
- 40 like.like();
- 41 //(3)若带参数,可去掉小括号简化,可去掉返回类型简化
- 42 //like = (int a,int b) -> System.out.println("I like lambda6");
- 43 //like = a,b -> System.out.println("I like lambda6");
- 44 }
- 45
- 46 }
- 47 interface ILike{ //函数式接口
- 48 void like();
- 49 }
- 50 //实现类
- 51 class Like1 implements ILike{
- 52 @Override
- 53 public void like() {
- 54 System.out.println("I like lambda1");
- 55 }
- 56 }
4、线程状态

5、停止线程
不推荐使用JDK提供的stop()、destroy()方法。
建议使用一个标志位进行终止变量,当flag=false,则终止线程运行。
- 1 public class TestStop implements Runnable{
- 2
- 3 //设置标志位
- 4 private boolean flag = true;
- 5
- 6 public static void main(String[] args) {
- 7 TestStop testStop = new TestStop();
- 8 new Thread(testStop).start(); //开启线程
- 9 for (int i = 0; i < 500; i++) {
- 10 if(i == 200){ //当主线程跑到200时,停止run线程
- 11 testStop.stop();
- 12 System.out.println("stop run");
- 13 }
- 14 System.out.println("main"+i);
- 15 }
- 16 }
- 17 //提供停止线程的方法,转换标志位
- 18 public void stop(){
- 19 this.flag = false;
- 20 }
- 21
- 22 @Override
- 23 public void run() {
- 24 int i = 0;
- 25 while (flag){
- 26 System.out.println("run"+ i++);
- 27 }
- 28 }
- 29 }
6、线程休眠 sleep()
7、线程礼让 yield()
8、线程强制执行 join()
9、线程状态观测
Thread.State state = thread.getState();
10、线程的优先级
- 1 public class TestPriority implements Runnable{
- 2 @Override
- 3 public void run() {
- 4 System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
- 5 }
- 6
- 7 public static void main(String[] args) {
- 8 //主线程
- 9 System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
- 10 TestPriority testPriority = new TestPriority();
- 11 Thread t1 = new Thread(testPriority);
- 12 Thread t2 = new Thread(testPriority);
- 13 Thread t3 = new Thread(testPriority);
- 14 Thread t4 = new Thread(testPriority);
- 15
- 16 t1.setPriority(Thread.MAX_PRIORITY);
- 17 t1.start();
- 18 t2.setPriority(Thread.MIN_PRIORITY);
- 19 t2.start();
- 20 t3.setPriority(8);
- 21 t3.start();
- 22 t4.setPriority(4);
- 23 t4.start();
- 24 }
- 25 }

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,要看cpu的调度。
11、守护线程 setDaemon()
12、线程同步
并发:同一个对象被多个线程同时操作。
线程同步:就是一种等待机制,多个需要同时访问此对象是线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用。
形成条件:队列 + 锁
在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。但也存在一些问题:
13、同步方法
(1)synchronized关键字包括两种用法:synchronized方法和synchronized块。
(2)synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized,将会影响效率。
- 1 public class SafeBuyTicket{
- 2 public static void main(String[] args) {
- 3 BuyTicket station = new BuyTicket();
- 4 new Thread(station ,"lily").start();
- 5 new Thread(station ,"Ming").start();
- 6 new Thread(station ,"Jenny").start();
- 7
- 8 }
- 9 }
- 10 class BuyTicket implements Runnable{
- 11 private int ticketNum = 10;
- 12 boolean flag = true;
- 13 @Override
- 14 public void run() {
- 15 while(flag){
- 16 try {
- 17 buy();
- 18 } catch (InterruptedException e) {
- 19 throw new RuntimeException(e);
- 20 }
- 21 }
- 22 }
- 23 //同步方法
- 24 private synchronized void buy() throws InterruptedException {
- 25 if(ticketNum <= 0){
- 26 flag = false;
- 27 return;
- 28 }
- 29 Thread.sleep(100);
- 30 System.out.println(Thread.currentThread().getName() + " get " + ticketNum--);
- 31 }
- 32 }
14、同步块
synchronized(obj){}
obj称之为同步监听器:
(1)obj可以是任何对象,但是推荐使用共享资源作为同步监视器
(2)同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class。
同步监视器的执行过程:
(1)第一个线程访问,锁定同步监视器,执行其中代码;
(2)第二个线程访问,发现同步监视器被锁定,无法访问;
(3)第一个线程访问完毕,解锁同步监视器;
(4)第二个线程访问,发现同步监视器没有锁,然后锁定并访问;
- 1 public class SafeList {
- 2 public static void main(String[] args) {
- 3 List
list = new ArrayList(); - 4 for (int i = 0; i < 1000; i++) {
- 5 new Thread(()->{
- 6 //代码块
- 7 synchronized (list){
- 8 list.add(Thread.currentThread().getName());
- 9 }
- 10 }).start();
- 11 }
- 12 try {
- 13 Thread.sleep(300);
- 14 } catch (InterruptedException e) {
- 15 throw new RuntimeException(e);
- 16 }
- 17 System.out.println(list.size());
- 18 }
- 19 }
CopyOnWriteArrayList是JUC包下的一个线程安全集合。
15、死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放的资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。
死锁避免方法:
(1)互斥条件:一个资源每次只能被一个进程使用;
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放;
(3)不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺;
(4)循环等条件:若干进程之前形成一种头尾相接的循环等待资源关系。
16、Lock
- 1 class A {
- 2 private final ReentrantLock lock = new ReentrantLock();
- 3 public void m(){
- 4 lock.lock();
- 5 try {
- 6 //保证线程安全的代码
- 7 }catch (Exception e){
- 8
- 9 }finally {
- 10 lock.unlock();
- 11 }
- 12 }
- 13 }
17、Lock与synchronized的对比
18、线程协作

生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
Java提供了几个方法解决线程之间的通信问题:
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IllegalMonitorStateException.
解决方式1:
并发协作模型“生产者/消费者模式”--->管程法
(1)生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
(2)消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
(3)缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区”。
解决方式2:
并发协作模型“生产者/消费者模式”--->信号灯法(通过标志位来实现)
19、线程池
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。解决思路,可以提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池子中,避免频繁创建销毁,实现重复利用。这样能减少创建新线程的时间,提高响应速度;重复利用线程池中线程,降低资源消耗;便于线程管理等。
JDK5.0起提供了线程池相关的API:ExecutorService和Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。
- 1 public class TestPool {
- 2 public static void main(String[] args) {
- 3 //创建服务,创建线程池
- 4 ExecutorService service = Executors.newFixedThreadPool(10);
- 5 //执行
- 6 service.execute(new MyThread());
- 7 service.execute(new MyThread());
- 8 service.execute(new MyThread());
- 9 service.execute(new MyThread());
- 10 //关闭连接
- 11 service.shutdown();
- 12 }
- 13
- 14 }
- 15
- 16 class MyThread implements Runnable{
- 17
- 18 @Override
- 19 public void run() {
- 20 System.out.println(Thread.currentThread().getName());
- 21 }
- 22 }