线程简介
程序:指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念
进程:执行程序的一次执行过程,它是一个动态的概念,是系统资源分配的单位
线程:线程就是独立的执行路径,也是CPU调度和执行的单位,通常一个进程可以包含多个线程,当然一个进程至少有一个线程,不然没有意义
注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
线程创建
三种创建方式:
1-Thread类
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
代码:
//创建线程方法一:继承Thread类,重写run()方法,调用start开启线程
//线程执行不是交替进行的,是有cpu调用
public class ThreadDemo extends Thread{
//重写run方法
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//创建线程对象
ThreadDemo demo = new ThreadDemo();
//调用start方法
demo.start();
for (int i = 0; i < 500; i++) {
System.out.println("123----"+i);
}
}
}
继承Thread类:
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
2-Runnable接口
- 定义myrunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start方法启动线程
代码:
//创建线程方式二:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class MyRunnable implements Runnable{
//重写run方法
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("123---"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
MyRunnable myRunnable = new MyRunnable();
//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread = new Thread(myRunnable);
thread.start();
for (int i = 0; i < 200; i++) {
System.out.println("asd---"+i);
}
}
}
实现Runnable接口:
- 实现接口Runnable具备多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
练习案例:模拟龟兔赛跑
//龟兔赛跑案例
public class TestThread1 implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
//模拟兔子睡觉
if (Thread.currentThread().getName().equals("兔子")&&i%10==0){
try{
Thread.sleep(10);
}catch (InterruptedException e){
System.out.println(e);
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
//判断是否完成比赛
private boolean gameOver(int steps){
//判断是否有胜利者
if (winner!=null){
return true;
}else {
if (steps>=100){
winner=Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
TestThread1 thread1 = new TestThread1();
new Thread(thread1,"兔子").start();
new Thread(thread1,"乌龟").start();
}
}
3-Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:Future<Boolean>result1 = ser.submit(t1);
- 获取结果:boolean r1 = result1.get();
- 关闭服务:ser.shutdownNow();
代码:
//线程创建方式三:Callable接口
public class Demo1 implements Callable<Boolean>{
@Override
public Boolean call() {
for (int i = 0; i < 20; i++) {
System.out.println("123--"+i);
}
return true ;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Demo1 testThread = new Demo1();
//创建服务
ExecutorService ser = Executors.newFixedThreadPool(1);
//提交执行
Future<Boolean> R1 = ser.submit(testThread);
//获取结果
boolean re1 = R1.get();
ser.shutdownNow();
}
静态代理
- 帮助真实对象做一些事情
- 静态对象和真实对象都要实现同一个接口
- 代理对象要代理真实对象
好处:
- 代理对象可以做很多真实对象做不了的事情
- 真实对象可以专注做自己的事情
案例代码:
public class TestMarry {
public static void main(String[] args) {
weddingCompany wedding1= new weddingCompany(new You());
wedding1.happyMarry();
}
}
//定义一个接口
interface Marry{
void happyMarry();
}
//定义真实对象类,做的事
class You implements Marry{
@Override
public void happyMarry() {
System.out.println("结婚了高兴!");
}
}
//代理角色,帮你做这件事
class weddingCompany implements Marry{
//代理谁
private Marry target;
public weddingCompany(Marry target){
this.target=target;
}
@Override
public void happyMarry() {
before();
this.target.happyMarry();//这就是真实对象
after();
}
private void after() {
System.out.println("完婚,收尾款");
}
private void before() {
System.out.println("婚前,布置现场");
}
}
Lamda表达式
lamda表达式的意义:
- 避免匿名内部类定义过多
- 可以让你的代码看起来很简洁
- 去掉了一推没有意义的代码,只留下核心的逻辑
函数式接口:
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
public interface Runnable{
public abstract void run();
}
Lamda表达式简化:
- 简化参数类型:多个参数时需要全部去掉参数类型
- 简化括号:单个参数时可以简化
- 简化代码块:代码坏内容为一行时可以简化
代码:
public class TestLamda {
//3.静态局部类
static class LamLike1 implements Lamda{
@Override
public void like(int a) {
System.out.println("Lamda-->"+a);
}
}
public static void main(String[] args) {
Lamda lamLike = new LamLike();
lamLike.like(1);
lamLike = new LamLike1();
lamLike.like(2);
//4.局部内部类
class LamLike2 implements Lamda{
@Override
public void like(int a) {
System.out.println("Lamda-->"+a);
}
}
lamLike = new LamLike2();
lamLike.like(3);
//5匿名内部类,没有类的名称,必须借助接口或父类
lamLike = new LamLike(){
@Override
public void like(int a) {
System.out.println("Lamda-->"+a);
}
};
lamLike.like(4);
//6.lamda表达式
lamLike = (int a)->{
System.out.println("Lamda-->"+a);
};
lamLike.like(5);
//7.简化数据类型
lamLike = (a)->{
System.out.println("Lamda-->"+a);
};
lamLike.like(6);
//8.简化括号
lamLike = a->{
System.out.println("Lamda-->"+a);
};
lamLike.like(7);
//9.简化代码块
lamLike = a-> System.out.println("Lamda-->"+a);
lamLike.like(8);
}
}
//1.定义一个函数式接口Lamda
interface Lamda{
void like(int a);
}
//2.定义一个实现类Lamlike
class LamLike implements Lamda{
@Override
public void like(int a) {
System.out.println("Lamda-->"+a);
}
}
线程状态
- 创建状态:线程对象一旦创建就进入了创建状态
- 就绪状态:当调用start()方法,线程就进入就绪状态,但不意味着立即调度执行
- 运行状态:进入运行状态,线程才真正的执行线程体的代码块
- 阻塞状态:当调用sleep、wait或同步锁定时,线程进入阻塞状态;就是代码不往下执行,阻塞事件解除后,重新进入就绪状态,等待cpu调度执行
- 死亡状态:线程中断或者结束,一旦进入死亡状态,就不能再次启动
线程方法:
- setPriority(int newPriority):更改线程优先级
- static void sleep(long mills):在指定的毫秒数内让当前正在执行的线程体休眠
- void join():暂停当前正在执行的线程对象,并执行其他线程
- static void yield():等待该线程终止
- void interrupt():中断线程,尽量不用
- boolean isAlive():测试线程是否处于活动状态
线程停止:
- 建议线程正常停止,利用次数,不建议死循环
- 建议使用标志位,设置一个标志位
- 不建议使用stop或destroy等过时或者不建议使用的方法
public class TestStop implements Runnable{
private boolean flag =true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("线程跑了"+i++);
}
}
public void stop(){
this.flag= false ;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if (i==900){
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
线程休眠:
- sleep(时间)指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException,需要抛出或try--catch
- sleep时间到达后线程进入就绪状态
- sleep可以模拟网络延时、倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
代码:模拟倒计时
//模拟倒计时
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
//tenDown();
//打印系统当前的时间
//获取系统当前时间
Date time = new Date(System.currentTimeMillis());
while (true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
//更新当前时间
time = new Date(System.currentTimeMillis());
}
}
//倒计时方法
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
线程礼让:但是不一定成功,看cpu心情
线程插队:Join方法
代码:
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程VIP来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 200; i++) {
if (i==100){
thread.join();
}
System.out.println("主线程"+i);
}
}
}
线程状态观测:Thread.State
代码:
//查看线程的状态
public class ThreadState {
public static void main(String[] args) throws InterruptedException {
Thread thread =new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("=======");
});
//观察线程状态
Thread.State state = thread.getState();
System.out.println(state);//new
//启动线程后的状态
thread.start();
state = thread.getState();
System.out.println(state);//run
//只要线程不终止就一直输出状态
while (state!= Thread.State.TERMINATED){
Thread.sleep(100);
//更新线程状态
state = thread.getState();
//状态输出
System.out.println(state);
}
}
}
线程优先级:权重1-10
- 设置优先级超过范围就会报错
- 优先级低的只是意味着被调用的概率低
- 默认的优先级为5
代码:
//测试线程优先级
public class TestPriority {
public static void main(String[] args) {
//获取主线程的优先级
System.out.println(Thread.currentThread().getName()+"==="+Thread.currentThread().getPriority());
Priority priority = new Priority();
Thread thread = new Thread(priority);
Thread thread1 = new Thread(priority);
Thread thread2 = new Thread(priority);
Thread thread3 = new Thread(priority);
Thread thread4 = new Thread(priority);
Thread thread5 = new Thread(priority);
thread.start();//默认优先级
//线程优先级先设置,再启动
thread1.setPriority(1);
thread1.start();
thread2.setPriority(4);
thread2.start();
thread3.setPriority(10);
thread3.start();
thread4.setPriority(2);
thread4.start();
thread5.setPriority(8);
thread5.start();
}
}
class Priority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==="+Thread.currentThread().getPriority());
}
}
守护线程:
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 后台记录操作日志、监控内存、垃圾回收等就是守护线程
代码:
//测试守护线程
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
//默认为false
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
new Thread(you).start();
}
}
//守护者
class God implements Runnable{
@Override
public void run() {
//让守护者一致跑着
while (true){
System.out.println("一直守着你");
}
}
}
//用户
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("活完一生");
}
System.out.println("==结束==");
}
}
线程同步
并发:同一个对象被多个线程同时操作
线程同步:就是一个等待机制,形成队列+锁保证安全性
同步方法:synchronized void 方法名()
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
同步块 synchronized (Obj){}:
- Obj称为同步监视器
- Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
同步监视器的执行过程:
- 线程1访问,锁定同步监视器,执行其中代码
- 线程2访问,发现同步监视器被锁定,无法访问
- 线程1访问完毕,解锁同步监视器
- 线程2访问,发现同步监视器没有锁,然后锁定并访问
示例代码:
//线程不安全的集合
//如果只用了synchronized同步快,没有使用sleep,也可能出现数据紊乱
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5000; i++) {
new Thread(()->{
//同步代码块
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());//输出:5000
}
}
JUC安全类型集合:
代码测试:
//测试JUC安全集合
public class TestJUC {
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList<String>list=new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
死锁:
多个线程相互抱着对方需要的资源,然后形成僵持
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求和保持条件:一个进程因请求资源而阻塞时,对方已获得的资源保持不放
- 不剥夺条件:进程已有的资源,在未完成之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
死锁避免方法:
上面列出死锁的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁发生
Lock显示锁
测试代码:
//测试lock
public class TestLock {
public static void main(String[] args) {
TestLock1 testLock1= new TestLock1();
new Thread(testLock1).start();
new Thread(testLock1).start();
new Thread(testLock1).start();
}
}
class TestLock1 implements Runnable{
int nums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();//加锁
if (nums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(nums--);
} else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}
线程协作
生产者:生产者生产产品等待消费者消费
消费者:消费者消费产品,消费完后等待生产者生产
解决方法1:利用缓冲区---管程法
代码示例:
package thread.thread;
//测试生成消费的解决方法:建立缓冲区---管程法
//需要有 生产者、消费者、产品、缓冲区
public class TestPC {
public static void main(String[] args) {
BufferArea bufferArea=new BufferArea();
Productor productor = new Productor(bufferArea);
CumsComer cumsComer = new CumsComer(bufferArea);
productor.start();
cumsComer.start();
}
}
//生成者
class Productor extends Thread{
BufferArea bufferArea;
public Productor( BufferArea bufferArea){
this.bufferArea=bufferArea;
}
//生成
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
bufferArea.push(new Product(i));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("生成了"+i+"个产品");
}
}
}
//消费者
class CumsComer extends Thread{
BufferArea bufferArea;
public CumsComer( BufferArea bufferArea){
this.bufferArea=bufferArea;
}
@Override
public void run(){
for (int i = 0; i < 100; i++) {
try {
System.out.println("消费了"+bufferArea.pop().id+"个产品");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
//产品
class Product{
int id;//产品编号
public Product(int id) {
this.id = id;
}
}
//缓冲区
class BufferArea{
//缓冲区大小
Product[] products = new Product[10];
//数量
int count=0;
//生产者放入产品
public synchronized void push(Product product) throws InterruptedException {
//如果容器满了,就等待消费者消费
if (count==products.length){
//通知消费者消费,生成等待
this.wait();
}
//如果没有满,就放入产品
products[count]=product;
count++;
//通知消费者,可以消费了
this.notifyAll();
}
//消费则消费产品
public synchronized Product pop() throws InterruptedException {
//判断能否消费
if (count==0){
//等待生成者生产
this.wait();
}
//如果可以消费
count--;
Product product=products[count];
//吃完了,通知生成者生成
this.notifyAll();
return product;
}
}
解决方法2:通过标志位---信号灯法
代码示例:
package thread.thread;
//测试生产者、消费者:信号灯法
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者---演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
this.tv.play("快乐大本营");
}else {
this.tv.play("抖音");
}
}
}
}
//消费者---观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.view();
}
}
}
//产品---节目
class TV{
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice ; //表演的节目
boolean flag = true ;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notifyAll();
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void view(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag=!this.flag;
}
}
线程池
线程池好处:
- 提高响应速度--减少创建新线程的时间
- 降低资源消耗--重复利用线程池中线程,不需要每次创建
- 便于线程管理
- 核心池的大小
- 最大线程数
- 线程没有任务时最多保持多长时间会终止
测试代码:
package thread.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//线程池
public class TestPool {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool:参数为线程池d大小
ExecutorService service= Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭服务
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+i);
}
}