Java 多线程
1.概述
Process 与 Thread:
- 说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
- 而进程则是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位
- 通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程就是CPU调度和执行的单位。
核心概念:
- 线程就是独立的执行路劲
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程、gc线程
- main() 称之为主线程,为系统的入口,用于执行整个程序
- 在一个进程冲,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如CPU调度的时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当就会造成数据不一致
2.线程创建
三种创建方式:
- 继承Thread 类 (重点)
- 实现Runnable 接口 (重点)
- 实现Callable 接口
//创建线程方式一:继承Thread类,重写run方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由CPU调度执行
public class TestThread extends Thread{
@Override
public void run() {
//run方法线程
for (int i = 0; i < 10; i++) {
System.out.println("我在学习 - " + i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建线程对象
TestThread testThread = new TestThread();
//调用start方法
testThread.start();
for (int i = 0; i < 10; i++) {
System.out.println("我在学习多线程 - " + i);
}
}
}
//创建线程方式二:实现Runnable接口,重写run方法,执行线程需要丢人runnable接口实现类,调用start方法
public class TestThread implements Runnable{
@Override
public void run() {
//run方法线程
for (int i = 0; i < 10; i++) {
System.out.println("我在学习 - " + i);
}
}
public static void main(String[] args) {
//创建Runnable 接口的实现类对象
TestThread testThread = new TestThread();
//创建线程对象,通过线程对象来开启我们的线程,代理
new Thread(testThread).start();
for (int i = 0; i < 10; i++) {
System.out.println("我在学习多线程 - " + i);
}
}
}
小结:
- 继承Thread 类
- 子类继承Thread类具备多线程能力
- 启动:子类对象.start()
- 不建议使用:避免OOP单继承局限性
- 实现Runnable接口
- 实现Runnable具有多线程能力
- 启动线程:传入目标对象 + Thread对象.start()
- 推荐使用:避免的单继承的局限性,灵活方便,方便同一个对象被多个线程使用
3.静态代理模式
public class Test {
public static void main(String[] args) {
company company = new company(new You());
company.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("我要结婚了!");
}
}
//代理角色
class company implements Marry{
private Marry target;
public company(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("结婚之前,布置现场");
}
}
总结:
- 真实对象和代理对象都要实现同一个接口
- 代理对象要代理真实角色
- 好处:
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注做自己的事情
4.Lambda 表达式
//推导lambda表达式
public class Test {
//3.静态内部类
static class Like2 implements ILike {
@Override
public void lambda() {
System.out.println("two");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
//4.局部内部类
class Like3 implements ILike {
@Override
public void lambda() {
System.out.println("three");
}
}
like = new Like3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("four");
}
};
like.lambda();
//6.用Lambda简化
like = () -> {
System.out.println("five");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike {
void lambda();
}
//2.实现类
class Like implements ILike {
@Override
public void lambda() {
System.out.println("one");
}
}
总结:
- lambda 表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹
- 前提是接口为函数式接口(只有一个方法)
- 多个参数也可以去掉参数类型,但是去掉就全部去掉,必须加上括号
5.线程状态
6.线程停止
//测试stop
//1.建议线程正常停止--->利用次数,不建议死循环
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class Test implements Runnable{
//1.设立一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("run......" + i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
Test test = new Test();
new Thread(test).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900) {
//调用stop方法切换标志位,让线程停止
test.stop();
System.out.println("线程改停止了");
}
}
}
}
7.线程休眠
- sleep(时间) 指定当前线程阻塞的毫秒数
- sleep 存在异常InterruptedException
- sleep 时间到达后线程进入就绪状态
- sleep 可以模拟网络延时,倒计时等
- 每个对象都有一个锁,sleep不会释放锁
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args){
Date startTime = new Date(System.currentTimeMillis());//打印当前系统时间
while (true) {
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <=0){
break;
}
}
}
}
8.线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CPU重新调度,礼让不一定成功!看CPU心情
//线程礼让Yield
public class Test{
public static void main(String[] args){
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始执行");
Thread.yield(); //线程礼让,但是不一定成功
System.out.println(Thread.currentThread().getName() + "线程停止执行");
}
}
9.线程强制执行
- join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞
- 可以想象成插队
//Join测试
public class Test implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程VIP来了" + i);
}
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
new Thread(test).start();
for (int i = 0; i < 1000; i++) {
if (i == 200) {
new Thread().join();
}
System.out.println("main" + i);
}
}
}
10.观测线程状态
//观测线程状态
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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); //输出状态
}
}
}
11.线程优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围1-10
- Thread.MIN_PRIORITY = 1
- Thread.MAX_PRIORITY = 10
- Thread.NORM_PRIORITY= 5
- 使用以下方式改变或者获取优先级
- getPriority() . setPriority(int xxx)
- 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
//线程的优先级
public class Test {
public static void main(String[] args){
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
//设置优先级,在启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY); //10
t4.start();
t5.setPriority(Thread.MIN_PRIORITY);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
12.守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
//守护线程
public class Test {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); //默认是false表示是用户线程,正常的线程都是用户线程
thread.start(); //上帝守护线程启动
Thread thread1 = new Thread(you); //你 用户线程启动
thread1.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("goodbye!");
}
}
13.线程同步机制
- 并发:同一个对象被多个线程同时操作
- 处理多线程问题是,多个线程访问同一个对象,并且谋些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用
- 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入了锁机制(synchronized),当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可
存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁,会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题
14.同步方法同步块
同步方法 :
同步块:
锁的是增删改的对象
15.死锁
避免死锁:
16.锁
测试代码:
import java.util.concurrent.locks.ReentrantLock;
//测试锁
public class Test {
public static void main(String[] args) {
Test2 test2 = new Test2();
new Thread(test2).start();
new Thread(test2).start();
new Thread(test2).start();
}
}
class Test2 implements Runnable {
int ticketNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();//加锁
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}
17.线程协作
-
线程通信
-
通信解决
18.管程法
//测试:生产者消费者模型 --> 利用缓冲区解决:管程法
//生产者、消费者、产品、缓冲区
public class Test {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
//生产者
class Producer extends Thread{
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了"+ i + "只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了" + container.pop().id + "只鸡");
}
}
}
//产品
class Chicken{
int id; //产品编号
Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken) {
//如果容器慢了,就等待消费者消费
if (count == chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count == 0){
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
19.信号灯法
//测试:生产者消费者模型 --> 利用标志位解决:信号灯法
public class Test {
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.watch();
}
}
}
//产品-->节目
class TV {
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice; //表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了" + voice);
//通知观众观看
this.notifyAll(); //通知唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch(){
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
20.线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class Test {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
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());
}
}