多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。具有这种能力的系统包括对称多处理机、多核心处理器以及芯片级多处理(Chip-level multithreading)或同时多线程(Simultaneous multithreading)处理器。在一个程序中,这些独立运行的程序片段叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理(Multithreading)”。
说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
而进程则是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位
通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位
注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
步骤
案例
package com.zheng.demo01;
/*
* @author 浩然
* @email [email protected]
*/
//创建线程方式一:继承Thread类,重写run()方法,调用start方法开启线程
//总结:注意,线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread {
@Override
public void run() {
//run 方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---" + i);
}
}
public static void main(String[] args) {
//main 线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---" + i);
}
}
}
步骤
定义MyRunnable类实现Runnable接口
实现run()方法,编写线程执行体
创建线程对象,调用start()方法启动线程
案例
package com.zheng.demo01;
/*
* @author 浩然
* @email [email protected]
*/
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类
public class TestThread3 implements Runnable {
@Override
public void run() {
//run 方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启我们的线程,代理
//Thread thread = new Thread(testThread3);
//thread.start();
new Thread(testThread3).start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---" + i);
}
}
}
输出结果和之前继承Thread差不多
继承Thread类
实现Runnable接口
案例
package com.zheng.demo01;
/*
* @author 浩然
* @email [email protected]
*/
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable {
//火车票的数量
private int ticketNums = 10;
@Override
public void run() {
while (true) {
if (ticketNums <= 0){
break;
}
System.out.println(Thread.currentThread().getName()+"-->拿到了第" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();
new Thread(testThread4,"小明").start();
new Thread(testThread4,"老师").start();
new Thread(testThread4,"黄牛").start();
}
}
规则
案例代码
package com.zheng.demo01;
/*
* @author 浩然
* @email [email protected]
*/
//模拟龟兔赛跑
public class Race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子") && i%10==0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
//如果比赛结束了,就停止程序
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了" + i+"步");
}
}
//判断是否完成比赛
private boolean gameOver(int steps){
//判断是否有胜利者
if (winner!=null){//已经存在胜利者了
return true;
}{
if (steps >= 100){
winner = Thread.currentThread().getName();
System.out.println("winner is" + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
代码案例
package com.zheng.lambda;
/*
* @author 浩然
* @email [email protected]
*/
/*
推到lambda表达式
*/
public class TestLambda1 {
//3. 静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda2");
}
}
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("i like lambda3");
}
}
like = new Like3();
like.lambda();
//5. 匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};
like.lambda();
//6. 用lambda简化
like = () -> {
System.out.println("i like lambda5");
};
like.lambda();
}
}
//1. 定义一个函数式接口
interface ILike{
void lambda();
}
//2. 实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda");
}
}
简化Lambda
代码实现
package com.zheng.lambda;
/*
* @author 浩然
* @email [email protected]
*/
public class TestLambda2 {
public static void main(String[] args) {
//1. lambda表达式简化
ILove love = (int a) -> {
System.out.println("i love you1-->" + a);
};
//简化1,去掉参数类型
love = (a)-> {
System.out.println("i love you1-->" + a);
};
//2. 简化括号
love = a->{
System.out.println("i love you1-->" + a);
};
//简化3,去掉花括号
love = a -> System.out.println("i love you1-->" + a);
love.love(521);
//总结:
//lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。
//提起是接口为函数式接口
//多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
}
}
interface ILove{
void love(int a);
}
**代理(Proxy)**是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象。
要求被代理类和代理类同时实现相应的一套接口;通过代理类的对象调用重写接口的方法时,实际上执行的是被代理类同样的方法的调用。
案例
package com.zheng.StaticProxy;
/*
* @author 浩然
* @email [email protected]
*/
//静态代理模式总结:
//真实对象和代理对象都要事先同一个接口
//代理对象要代理真实角色,
//好处:
//代理对象可以做到很多真实对象做不了的事情
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
You you = new You();//你要结婚
new Thread( () -> System.out.println("我爱你")).start();
new WeddingCompany(new You()).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("结婚之前布置场地");
}
}
运行结果
我爱你
结婚之前布置场地
浩然要工作了,开心!
结婚之后,收尾款
案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//测试stop
//1. 建议线程正常停止--->利用次数,不建议死循环
//2. 建议使用标志位--->设置一个标志位
//3. 不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable {
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run....Thread" + i++);
}
}
//2. 设置一个公开的方法停止线程,转换标志位
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){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
时间倒计时案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时,,,
public class TestSleep2 {
public static void main(String[] args) {
//try {
// tenDown();
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
//打印当前系统时间
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;
}
}
}
}
案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {
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() +"线程停止执行");
}
}
案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//测试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 < 500; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main" + i);
}
}
}
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//观察现成的状态
public class TestState {
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) {
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);//更新线程状态
}
}
}
java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1~10
使用以下方式改变或获取优先级
注意:优先级的设定建议在start()调度之前,优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//测试线程的优先级
public class TestPriority{
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);
Thread t6 = new Thread(myPriority);
//先设置优先级,在启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
t4.start();
t5.setPriority(8);
t5.start();
t6.setPriority(7);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->"+ Thread.currentThread().getPriority());
}
}
案例
package com.zheng.state;
/*
* @author 浩然
* @email [email protected]
*/
//测试守护线程
//上帝守护你
public class TestDaemon {
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();//上帝守护线程
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("你一生都开心的或者" + i);
}
System.out.println("=======goodbye!world=========");
}
}
线程同步
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排他锁,独占资源,其他线程则必须等待,使用后释放锁即可,存在以下问题:
由于我们可以通过 private 关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是 synchrnized 关键字,它包括两种方法:synchronized 方法和 synchronized块
synchronized方法控制对"对象"访问,每个对象对应一把锁,每个synchronized方法都不许获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一但执行,就独占该锁,知道该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
方法里面需要修改的内容才需要锁,锁的太多,浪费资源
案例
package com.zheng.thread;
/*
* @author 浩然
* @email [email protected]
*/
//死锁:多个线程互相抱着对方需要的资源,形成僵持。
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑凉");
Makeup g2 = new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){//一秒钟后想获得镜子
System.out.println(this.girlName+ "获得镜子的锁");
}
}else {
synchronized (mirror){//获得口红的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//一秒钟后想获得镜子
System.out.println(this.girlName+ "获得口红的锁");
}
}
}
}
产生死锁的四个必要条件
注意:上面列出了思索地四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁的发生
案例
package com.zheng.gaoji;
/*
* @author 浩然
* @email [email protected]
*/
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 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 {
ticketNums--;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
分析
这是一个线程同步问题,生产者和消费者共享一个资源,并且生产者和消费者之间相互依赖,互为条件
并发协作模式:“生产者”/“消费者模式” —>管理法
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
案例
package com.zheng.gaoji;
/*
* @author 浩然
* @email [email protected]
*/
//测试:生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了" + i + "鸡");
container.push(new Chicken(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++) {
try {
System.out.println("消费了-->"+ container.pop().id +"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
class Chicken{
int id;//产品编号
public 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() throws InterruptedException {
//判断能否消费
if (count == 0) {
//等待生产者生产,消费者等待
this.wait();
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
案例
package com.zheng.gaoji;
/*
* @author 浩然
* @email [email protected]
*/
//测试生产者消费者问题2:信号灯法,标志位解决
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.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;
}
}
————————————————————
案例
package com.zheng.gaoji;
/*
* @author 浩然
* @email [email protected]
*/
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
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());
//2. 关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}