Java多线程学习记录
1 Java多线程简要概述
1.1线程的核心概念
(1)线程就是独立执行的路径
(2)在程序运行时,即使没有自己创建线程,后台也会有多个线程,比如 主线程,gc线程
(3)main()称之为主线程,为系统的入口,用于执行整个程序
(4)在一个进程中,如果避开了多个线程,现成的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
(5)对同一份资源进行操作时,会存在资源抢夺的问题,需要加入并发控制
(6)线程会带来额外的开销,如cpu调度时间,并发控制开销
(7)每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
2 线程的创建
2.1 继承Thread
(1)继承Thread类,重写run方法,调用Start()方法开启线程
(2)不建议使用:为了避免OOP单继承的局限性
(3)代码展示
package com.shallow.多线程;
// 创建线程方法一:继承Thread类,重写run方法,调用Start()方法开启线程
public class ThreadTest1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 1200; i++) {
System.out.println("Thread多线程" + i);
}
}
public static void main(String[] args) {
ThreadTest1 threadTest = new ThreadTest1(); // 创建一个线程对象
threadTest.start(); // 调用start()方法开启线程
for (int i = 0; i < 1200; i++) {
System.out.println("main主线程" + i);
}
}
}
// 打印结果
main主线程0
Thread多线程0
Thread多线程1
Thread多线程2
Thread多线程3
Thread多线程4
main主线程1
Thread多线程5
.....
可以看得出来,这两个线程是同时在进行的
2.2 实现Runnable接口
(1)重写run方法,执行线程需要丢入runnable接口实现类。调用start()方法
(2)推荐使用:很好的避免了单继承的局限性,灵活方便,同一个对象被多个线程使用
(3)代码展示
package com.shallow.多线程;
public class RunnableTest implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1200; i++) {
System.out.println("Runnable线程:" + i);
}
}
public static void main(String[] args) {
RunnableTest runnableTest = new RunnableTest();
new Thread(runnableTest).start();
for (int i = 0; i < 1200; i++) {
System.out.println("main方法:" + i);
}
}
}
// 打印结果
main方法:0
Runnable线程:0
Runnable线程:1
Runnable线程:2
main方法:1
main方法:2
main方法:3
main方法:4
Runnable线程:3
....
2.3 实现Callable接口
(1)创建方法
1.创建一个实现Callable接口的类,实现call方法。将操作声明在call里。
2.创建Callable接口实现类的对象。然后创建执行服务,在提交服务,最后记得要关闭服务
(2)代码展示
package com.shallow.多线程;
import java.util.concurrent.*;
public class CallableTest1 implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "Callable:" + i);
}
return true;
}
public static void main(String[] args) throws Exception{
CallableTest1 callableTest1 = new CallableTest1();
CallableTest1 callableTest2 = new CallableTest1();
CallableTest1 callableTest3 = new CallableTest1();
// 创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> future1 = executorService.submit(callableTest1);
Future<Boolean> future2 = executorService.submit(callableTest2);
Future<Boolean> future3 = executorService.submit(callableTest3);
// 获取结果
boolean b1 = future1.get();
boolean b2 = future2.get();
boolean b3 = future3.get();
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
// 关闭服务
executorService.shutdownNow();
}
}
// 打印
pool-1-thread-3Callable:2
pool-1-thread-3Callable:3
pool-1-thread-3Callable:4
pool-1-thread-3Callable:5
pool-1-thread-3Callable:6
pool-1-thread-3Callable:7
pool-1-thread-1Callable:0
pool-1-thread-2Callable:0
pool-1-thread-2Callable:1
看这个3Callable和1Callable还有2Callable同时在输出
3 线程状态
3.1 五大状态
(1)五大状态
1. 创建状态
2. 就绪状态
3. 运行状态
4. 阻塞状态
5. 死亡状态
3.2 停止线程
(1)使用标志位方式
(2)代码展示
package com.shallow.多线程;
public class StopThread_04 implements Runnable{
// 设置标志位
private boolean stop = true;
@Override
public void run() {
int i = 0;
while (stop) {
System.out.println("Run...." + i);
}
}
// 写一个标志位,用来停止某个线程
public void stop() {
this.stop = false;
}
public static void main(String[] args) {
StopThread_04 stopThread = new StopThread_04();
new Thread(stopThread).start();
for (int i = 0; i < 500; i++) {
System.out.println("main...." + i);
if (i == 490) {
// 调用stop方法停止线程
stopThread.stop();
System.out.println("run线程停止了");
}
}
}
}
// 打印
main....0
Run....0
main....1
Run....0
main....2
Run....0
...
main....490
Run....0
run线程停止了
3.3 线程休眠(阻塞状态)
PS:每一个对象都有一把锁,sleep不会释放锁
(1)sleep() 的作用是让当前线程休眠,即当前线程会从“运行状态”进入到“休眠(阻塞)状态”。sleep()会指定休眠时间,线程休眠的时间会大于/等于该休眠时间;在线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行。
(1)代码展示
package com.shallow.多线程;
import java.text.SimpleDateFormat;
import java.util.Date;
// 线程休眠
public class ThreadSleep_05 {
public static void main(String[] args) throws InterruptedException {
// ThreadSleep_05.tenDown(); // 这个方法是模拟倒计时
// 模拟打印系统当前时间
Date Time = new Date(); // 获取当前时间
while (true) {
Thread.sleep(1000); // 休眠1秒
long time = Time.getTime(); // 将时间转换为long类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); // 将获取的时间格式化
String format = simpleDateFormat.format(time); // 将long类型的时间转换为字符串形式
System.out.println(format);
Time = new Date(); // 从新获取时间起到更新时间的作用
}
}
// 模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 30;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
// 打印
14:05:04
14:05:05
14:05:06
14:05:07
14:05:08
14:05:09
14:05:10
14:05:11
即休眠一秒
3.4 线程礼让
(1)首先礼让是不一定成功的
(2)礼让线程,让当前正在执行的线程暂停,但不阻塞
(3)将线程从运行状态转为就绪状态
(4)代码展示
package com.shallow.多线程;
public class ThreadYield_06 implements Runnable{
public static void main(String[] args) {
ThreadYield_06 threadYield = new ThreadYield_06();
new Thread(threadYield, "李白").start();
new Thread(threadYield, "李清照").start();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始");
Thread.yield(); // 线程礼让方法
System.out.println(Thread.currentThread().getName() + "线程结束");
}
}
// 打印情况1:礼让成功
李清照线程开始
李白线程开始
李清照线程结束
李白线程结束
// 礼让不成功
李白线程开始
李白线程结束
李清照线程开始
李清照线程结束
3.5 合并线程(插队)
(1)顾名思义插队就是有些线程它需要优先去执行
(2)代码展示
package com.shallow.多线程;
public class ThreadJoin_07 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("vip插队" + i);
}
}
public static void main(String[] args) {
ThreadJoin_07 threadJoin = new ThreadJoin_07();
Thread thread = new Thread(threadJoin);
thread.start();
for (int i = 0; i < 500; i++) {
if (i == 150) { // 当i= 150 时,开始插队,插队线程执行完另一个才会继续
try {
thread.join(); // 插队方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main" + i);
}
}
}
// 打印
main149
vip插队64
vip插队65
vip插队66
vip插队67
....
vip插队997
vip插队998
vip插队999
main150
main151
3.6 观察状态
(1)代码展示
package com.shallow.多线程;
public class StateThread_08 {
public static void main(String[] args) {
Thread thread = new Thread( () -> {
for (int i = 0; i < 5; 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); // RUNNABLE 在Java虚拟机中执行的线程处于此状态。
while (state != Thread.State.TERMINATED) { // 只要线程不终止,就一直输出
try {
Thread.sleep(100);
state = thread.getState(); // 更新线程状态
System.out.println(state);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4 线程优先级
4.1 线程优先级
(1)优先级一共分为1-10 越大级别越高 默认情况下为5
(2)最重要的一点,并不是一定高的就执行快。线程的优先级和执行顺序无关
(3)代码展示
package com.shallow.多线程;
public class ThreadPriority implements Runnable{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() +
"--->" + Thread.currentThread().getPriority());
ThreadPriority threadPriority = new ThreadPriority();
Thread thread1 = new Thread(threadPriority);
Thread thread2 = new Thread(threadPriority);
Thread thread3 = new Thread(threadPriority);
Thread thread4 = new Thread(threadPriority);
Thread thread5 = new Thread(threadPriority);
Thread thread6 = new Thread(threadPriority);
// 设置优先级
thread1.start();
thread2.setPriority(5);
thread2.start();
thread3.setPriority(9);
thread3.start();
thread4.setPriority(10);
thread4.start();
thread5.setPriority(2);
thread5.start();
thread6.setPriority(3);
thread6.start();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
"--->" + Thread.currentThread().getPriority());
}
}
// 打印
main--->5
Thread-0--->5
Thread-2--->9
Thread-1--->5
Thread-3--->10
Thread-5--->3
Thread-4--->2
由此可以看出10级并没有第一个执行完
5 守护(daemon)线程
5.1 守护(daemon)线程
(1)线程分为用户线程和守护线程
(2)守护线程要在thread.start()之前设置
(3)主线程结束,守护线程自动销毁
(4)代码展示
package com.shallow.多线程;
public class DaemonTest implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("守护线程守护着你!!!");
}
}
public static void main(String[] args) {
DaemonTest daemonTest = new DaemonTest();
You you = new You();
Thread thread = new Thread(daemonTest);
thread.setDaemon(true); // 默认为false,即正常线程
thread.start(); // 守护线程启动
new Thread(you).start();
}
}
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 365; i++) {
System.out.println(i + ":<<<<<<<<<<活着!!!>>>>>>>>>>>");
}
System.out.println("<<<<<<<<<<<<<<<<<Good By>>>>>>>>>>>>>>>>>");
}
}
6 线程同步
6.1 买票问题
(1)代码展示
package com.shallow.多线程;
// 买票问题
public class ThreadSynchronization1 implements Runnable{
private int count = 15;
boolean flag = true;
public static void main(String[] args) {
ThreadSynchronization1 ts = new ThreadSynchronization1();
new Thread(ts, "李白").start();
new Thread(ts, "李清照").start();
new Thread(ts, "纳兰性德").start();
}
@Override
public void run() {
while (flag) {
buy();
}
}
// synchronized同步方法 锁的是this
public synchronized void buy() {
if (count <= 0) {
flag = false;
return;
}
// 模拟延时
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "买到了" + count--);
}
}
// 打印
李白买到了10
李白买到了9
李白买到了8
李白买到了7
李白买到了6
李白买到了5
李白买到了4
李白买到了3
李白买到了2
李白买到了1
6.2 银行取钱问题
(1)代码展示
package com.shallow.多线程;
public class ThreadSynchronization2{
public static void main(String[] args) {
// 创建转户
Account account = new Account(1500, 201437);
Bank bank = new Bank(account, 1450, "李白");
Bank bank1 = new Bank(account, 250, "李清照");
bank.start();
bank1.start();
}
}
// 转户类
class Account {
public int money;
public int id;
public Account(int money, int id) {
this.money = money;
this.id = id;
}
}
// 银行:模拟取款
class Bank extends Thread {
public Account account; // 转户
public int subMoney; // 取多少钱
public int newMoney; // 现在手里多少钱
public Bank(Account account, int subMoney, String name) {
super(name);
this.account = account;
this.subMoney = subMoney;
}
// 取钱
@Override
public void run() {
/** synchronized默认锁的是this,也就是当前对象
* 所以使用同步块指定锁的对象
* 锁的对象是变化的量,即增删改的对象
*/
synchronized (account) {
// 先判断转户还有没有钱
if (account.money - subMoney <= 0) {
System.out.println(this.getName() + "钱不够了,取不了");
return;
}
// 延迟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 余额
account.money -= subMoney;
// 手里现在的钱
newMoney += subMoney;
System.out.println(account.id + "的余额为" + account.money);
System.out.println(this.getName() + "手里的钱有" + newMoney);
}
}
}
//
201437的余额为50
李白手里的钱有1450
李清照钱不够了,取不了
6.3 List集合问题
(1)代码展示
package com.shallow.多线程;
import java.util.ArrayList;
import java.util.List;
public class ThreadSynchronization3 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
//
10000
7 死锁
7.1 什么是死锁
(1)多个线程互相抱着对方的需要资源,然后形成僵持
7.2 产生死锁的必要条件
(1)互斥条件:一个资源每次只能被一个进程使用
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
(3)③不剥夺条件:进程以获得的资源,在未使用完之前,不能强行剥夺
(4)④循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
PS:根据上面的四个死锁必要条件,我们可以想办法避免死锁
(5)代码展示
package com.shallow.多线程;
public class DeadLockTest {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "李白");
Makeup makeup1 = new Makeup(1, "李清照");
makeup.start();
makeup1.start();
}
}
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread {
// 需要的资源
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
// 选择
int choice;
// 使用的人
String name;
Makeup(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
// 使用
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// makeup方法
public void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) {
System.out.println(this.name + "获得lipstick的锁");
Thread.sleep(1000);
}
synchronized (mirror) {
System.out.println(this.name + "获得mirror的锁");
}
} else {
synchronized (mirror) {
System.out.println(this.name + "获得mirror的锁");
Thread.sleep(2000);
}
synchronized (lipstick) {
System.out.println(this.name + "获得lipstick的锁");
}
}
}
}
//
李白获得lipstick的锁
李清照获得mirror的锁
李清照获得lipstick的锁
李白获得mirror的锁
8 lock锁
8.1 lock与synchronized对比
(1)lock是显示锁(手动开启锁和关闭锁)synchronized是隐式锁,出来作用域自动关闭
(2)lock只有代码块锁,synchronized有方法锁和代码块锁
(3)使用lock锁。Jvm将花费更少的时间来调度线程,性能更好,并且具有更好的扩展性
(4)优先使用顺序:Lock > 同步代码块>同步方法
(5)代码展示
package com.shallow.多线程;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest_14 implements Runnable{
private int count = 5;
boolean flag = true;
private ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
LockTest_14 lockTest = new LockTest_14();
new Thread(lockTest, "李白").start();
new Thread(lockTest, "李清照").start();
new Thread(lockTest, "纳兰性德").start();
}
@Override
public void run() {
while (true) {
try {
// 加锁
lock.lock();
if (count > 0) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count--);
}
else {
break;
}
}finally {
// 解锁
lock.unlock();
}
}
}
}
//
5
4
3
2
1
9 线程协作
9.1 管程法
(1)代码展示
package com.shallow.多线程;
public class Cooperation1 {
public static void main(String[] args) {
Buffer buffer = new Buffer();
new Production(buffer).start();
new Consumption(buffer).start();
}
}
// 生产者
class Production extends Thread {
Buffer buffer;
public Production(Buffer buffer) {
this.buffer = buffer;
}
// 生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
buffer.push(new Product(i));
System.out.println("生产了第" + i + "个产品");
}
}
}
// 消费者
class Consumption extends Thread {
Buffer buffer;
public Consumption(Buffer buffer) {
this.buffer = buffer;
}
// 消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了第" + buffer.pop().id + "个产品");
}
}
}
// 产品
class Product {
int id;
public Product(int id) {
this.id = id;
}
}
// 缓冲区
class Buffer {
// 需要一个容器大小
Product[] products = new Product[10];
// 计数
int count = 0;
// 生产者放入产品方法
public synchronized void push(Product p) {
// 判断 如果产品满了
if (count == products.length) {
// 通知消费者来消费
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有满
products[count] = p;
count++;
// 通知消费者消费
this.notifyAll();
}
// 消费者方法
public synchronized Product pop() {
// 判断消费者能否消费
if (count == 0) {
// 等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消费
count--;
Product product = products[count];
// 消费完了,通知生产
this.notifyAll();
return product;
}
}
9.2 信号灯法
(1)代码展示
package com.shallow.多线程;
public class Cooperation2_16 {
public static void main(String[] args) {
TaoBao taoBao = new TaoBao();
new Production1(taoBao).start();
new Consumption1(taoBao).start();
}
}
class Production1 extends Thread {
TaoBao taoBao;
public Production1(TaoBao taoBao) {
this.taoBao = taoBao;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.taoBao.push(i);
}
}
}
class Consumption1 extends Thread {
TaoBao taoBao;
public Consumption1(TaoBao taoBao) {
this.taoBao = taoBao;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.taoBao.buy();
}
}
}
class TaoBao {
int id;
boolean flag = true; // 标志位
// 生产
public synchronized void push(int id) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产了第" + id + "件物品");
this.notifyAll(); // 通知消费者购买
this.id = id;
this.flag = !this.flag;
}
// 消费
public synchronized void buy() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("用户购买了第" + this.id + "件物品");
// 通知生产
this.notifyAll();
this.flag = !this.flag;
}
}
10 线程池
10.1 线程池
(1)代码展示
package com.shallow.多线程;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool implements Runnable{
public static void main(String[] args) {
// 创建服务线程池(参数即为线程池大小)
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.execute(new ThreadPool());
executorService.execute(new ThreadPool());
executorService.execute(new ThreadPool());
executorService.execute(new ThreadPool());
// 关闭线程池
executorService.shutdown();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
PS:到这里结束,希望各位大佬能指点一二