1 多线程实现方式
共三种:继承Thread类,实现Runnable方法,实现Callable接口(了解)
1.1 Thread类
1.1.1 具体步骤
1,自定义线程类继承Thread类
2,重写run()方法,编写线程执行体
3,创建线程对象,调用start()方法启动
1.1.2 注意点
1,线程对象调用run方法则不会有多线程的效果
下面展示一些 内联代码片
。
package com.huanglk;
//创建相册方式1.基础Thread类,重写run方法,调用start开启线程
public class TestThread extends Thread{
private String name;
@Override
public void run(){
for (int i = 0;i<200;i++){
System.out.println(name+"name "+i);
}
}
public TestThread(String name) {
this.name = name;
}
public static void main(String[] args) {
TestThread testThread = new TestThread("testThread1111111");
TestThread testThread2 = new TestThread("testThread2222222");
// testThread2执行完之后在进行,testThread,
testThread2.run();
testThread.start();
for (int i = 0;i<1000;i++){
System.out.println("action "+i);
}
}
}
```java
执行效果:
testThread2222222name 1-200先全部输出
testThread1111111name 1-200和action 1-1000交叉输出
1.2 实现Runnable接口
1.2.1 具体步骤
1,创建实现Runnable接口的对象
2,启动线程:传入目标对象+Thread对象.start()
3,推荐使用:避免单继承得局限性,灵活方便,方面同个对象被多个线程使用
package com.huanglk;
//继承Thread类:1,子类继承Thread类具备多线程能力,2,启动线程:子类对象.start(),3,不建议使用:避免(面向对象)OOP单继承局限性
//实现Runnable接口:1,实现接口Runnable具有多线程能力,2,启动线程:传入目标对象+Thread对象.start(),3,推荐使用:避免单继承得局限性,灵活方便,方面同个对象被多个线程使用
//创建Runnable接口,重写run方法,执行现场需要重写runnable接口实现类,调用start方法
public class Thread3 implements Runnable{
@Override
public void run(){
for (int i = 0;i<200;i++){
System.out.println("test "+i);
}
}
public static void main(String[] args) {
//创建runnable接口实现类对象,
Thread3 testThread = new Thread3();
//创建线程对象,通过线程对象来开启我们得线程,代理,直接使用Thread3.run()无法实现多线程,只能执行单线程
Thread thread = new Thread(testThread);
thread.start();
for (int i = 0;i<1000;i++){
System.out.println("action "+i);
}
}
}
1.3 实现Callable接口(了解即可)
1,实现Callable接口,需要返回值类型
2,重写call方法,需要抛出异常
3,创建目标对象
4,传教执行服务:
ExecutorService ser = Executors.newFixedThreadPool(1);
5,提交执行:Future result1 = ser.submit(t1);
6,获取结果:boolean r1 = result1.get()
7,关闭服务:ser.shutdownNow();
package com.huanglk.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//创建相册方式1.基础Thread类,重写run方法,调用start开启线程
public class TestThread2 extends Thread{
private String url;
private String name;
public TestThread2(String url,String name){
this.name = name;
this.url = url;
}
@Override
public void run(){
webDownloader webDownloader = new webDownloader();
webDownloader.downLoader(url,name);
System.out.println("xiazai wanc "+name);
}
public static void main(String[] args) {
TestThread2 testThread1 = new TestThread2("https://www.kuangstudy.com/assert/course/c1/13.jpg","t1.jpg");
TestThread2 testThread2 = new TestThread2("https://www.kuangstudy.com/assert/course/c1/14.jpg","t2.jpg");
TestThread2 testThread3 = new TestThread2("https://www.kuangstudy.com/assert/course/c1/15.jpg","t3.jpg");
testThread1.run();
testThread2.start();
testThread3.start();
}
}
class webDownloader{
public void downLoader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
}catch (IOException e){
System.out.println("IOException " + e.getMessage());
}
}
}
1.3.1 callable接口优点
1,可以定义返回值
2,可以抛出异常
1.4 Thread类和Runnable接口使用注意点
继承Thread类:1,子类继承Thread类具备多线程能力,2,启动线程:子类对象.start(),3,不建议使用:避免(面向对象)OOP单继承局限性
实现Runnable接口:1,实现接口Runnable具有多线程能力,2,启动线程:传入目标对象+Thread对象.start(),3,推荐使用:避免单继承得局限性,灵活方便,方面同个对象被多个线程使用
创建Runnable接口,重写run方法,执行现场需要重写runnable接口实现类,调用start方法
1.5 多个线程操作出现的线程不安全问题案例
package com.huanglk.thread;
//多个线程同时操作一个对象
public class TestThread4 implements Runnable{
// 票数
private int ticketNum = 10;
@Override
public void run() {
while(true){
if (ticketNum<=0){
break;
}
// 模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+"-----拿到了第"+ticketNum--+" 张票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛党").start();
}
}
输出是出现多人抢占到同一张票
1.6 模拟龟兔赛跑案例
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){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"====跑了 "+i+" 步");
}
}
private boolean gameOver(int steps){
//判断是否有胜利者
if (null!=winner){
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();
}
}
1.7 线程状态
1.7.1 线程状态观测
1,线程状态。 线程可以处于以下状态之一:
NEW
尚未启动的线程处于此状态。
RUNNABLE
在Java虚拟机中执行的线程处于此状态。
BLOCKED
被阻塞等待监视器锁定的线程处于此状态。
WAITING
正在等待另一个线程执行特定动作的线程处于此状态。
TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
TERMINATED
已退出的线程处于此状态。
package com.huanglk.thread;
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);
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);
while(state!=Thread.State.TERMINATED){ //只要线程不终止,就一致输出状态
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
1.7.3 停止线程
1,不推荐使用JDK提供的stop(),destroy() 方法(废弃)
2,推荐线程自己停下来
3,建议使用一个标志位精选终止变量(当flag==false是停止)
package com.huanglk.thread;
//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++);
}
}
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("线程该停止了");
}
}
}
}
1.8 线程休眠
1,sleep(时间) 指定当前线程阻塞的毫秒数;
2,sleep存在异常InterruptedException
3,sleep时间达到后进入就绪状态;
4,sleep可以模拟网络延迟,发达线程问题的发生性
5,每个对象都有一个锁,sleep不会释放锁
(类似a线程进去后,a出去和b一起再让cpu进行选择)并不是让别人先走,而是退回起点重启起跑
1.9 线程礼让
1,礼让线程,让当前正在执行的线程暂停,但不阻塞
2,将线程从运行专题转换位就绪状态
3,让cpu重写调度,礼让不一定成功,看cpu
package com.huanglk.thread;
// 礼让不一定成功看cpu心情
public class TestYied {
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()+"线程停止执行");
}
}
1.10 线程强制执行(join)
1,join 合并线程,待此线程执行完成后,再执行其它线程,其它线程阻塞
2,类似插队
package com.huanglk.thread;
//测试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) {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0;i<1000;i++){
if (i==200){
try {
System.out.println("插队");
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main "+ i);
}
}
}
1.11 线程的优先级
1,Java提供一个线程调度器来健康程序中启动后进入就绪专题的所有线程,线程调度器按照优先级决定哪个线程来执行
2,但线程执不执行看cpu调,类似100张彩票和1张彩票的概率
3,线程优先级用数字表示,范围1-10,数字越大越高,默认5
4,使用getPriority(),setPriority(in xxx) 获取和改变优先级
package com.huanglk.thread;
public class TestPriority {
public static void main(String[] args) {
System.out.println("主线程默认优先级,为5");
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority,"t1");
Thread t2 = new Thread(myPriority,"t2");
Thread t3 = new Thread(myPriority,"t3");
Thread t4 = new Thread(myPriority,"t4");
//先设置优先级再启动
t2.setPriority(1);
t3.setPriority(4);
t4.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==="+Thread.currentThread().getPriority());
}
}
1.12 守护线程
1,线程分为用户线程和守护线程 setDaemon
2,虚拟机必须确保用户线程执行完毕
3,虚拟机不用等待守护线程执行完毕
4,如后台记录操作日志,监控内存,垃圾回收等待
package com.huanglk.thread;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
People people = new People();
Thread g = new Thread(god);
g.setDaemon(true);
g.start();
Thread you = new Thread(people);
you.start();
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝守护着你");
}
}
}
class People implements Runnable{
@Override
public void run() {
for (int i=0;i<36500;i++){
System.out.println("你一生开心的或者");
}
System.out.println("===goodbye god===");
}
}
1.13 线程同步
多个线程操作同一个资源
1.13.1 队列和锁
排队上厕所,排队队就是队列,锁则是厕所门
1,每个人都有一个锁
2,队列加锁解决线程安全问题
3,synchronized 锁机制 ,当一个线程获得对象的排他锁,独享资源,其它线程必须等待使用后释放锁
问题:
一个线程持有锁会导致其它所有需要此锁的线程挂起
多线程竞争加锁和释放锁会导致较多的上下文切换和调度延迟,引起性能问题
如果一个优先级高的线程等待一个优先级低的线程,释放锁会导致优先级倒置,引起性能问题。(如一个拉肚子的人和摸鱼的人抢一个厕所)
1.13.2 同步方法
使用synchronized方法和synchronized块
synchronized方法控制对 对象 的访问,每个对象一把锁,每个synchronized方法都必须调用该方法的对象的锁才能被执行,否则会阻塞,方法一旦执行,就独占该锁,知道该方法返回才释放锁,后面阻塞的线程才嫩获取锁,举行执行
1.13.3 sychronized方法块
1,修饰方法
//线程不安全有负数等情况
public class UnSafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"老师").start();
new Thread(buyTicket,"学生").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
private int ticketNum = 1000;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNum<=0){
flag = false;
return;
}
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + "拿到票号:" + ticketNum--);
}
}
package com.huanglk.syn;
public class TestBank {
public static void main(String[] args) {
//账号
Account account = new Account(50,"基金");
Drawing you = new Drawing(account,50,"你");
Drawing girlFriend = new Drawing(account,50,"girlFriend");
you.start();
girlFriend.start();
}
}
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing( Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run(){
//锁的对象,就是变化的量,需要增删改的量
synchronized (account) {
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + " 余额不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
class Account {
int money ;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//ArrayList是不安全的,但其中CopyOnWriteArrayList中lock则是list变线程安全
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(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
1.14 死锁
1,多个线程各自占用一些共享自愿,并且互相等待其它线程占用的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有 两个以上对象的锁 时,就有可能发生死锁问题
package com.huanglk.syn;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class TestLock {
public static void main(String[] args) {
MakeUp g1 = new MakeUp(0,"girlA");
MakeUp g2 = new MakeUp(1,"girlB");
g1.start();
g2.start();
}
}
class Lipstick{
}
class Mirror{
}
class MakeUp extends Thread{
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.getName()+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.getName()+"获得口红的锁");
}
}
}
}
}
1.14.1 死锁产生的四个条件
1,互斥条件:一个资源每次只能被一个进程使用。
2,请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
3,不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
4,循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。.
1.15 锁Lock
显示锁lock
隐式锁synchronized
1,ReentrantLock可重复锁
package com.huanglk.syn;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock1 {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2,"testA").start();
new Thread(testLock2,"testB").start();
new Thread(testLock2,"testC").start();
}
}
class TestLock2 implements Runnable{
int ticketNum = 1000;
// 定义lock锁
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
lock.lock();//加锁
try {
if (ticketNum > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ ticketNum--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
1.15.2 synchronized与Lock对比
1,Lock是显式锁(手动开启和关闭的锁)synchronized是隐式锁,出作用域自动释放
2,Lock只用代码块锁,synchronized有代码块锁和方法锁
3,使用Lock锁,JVM将花费较少的时间调度线程,性能较好,并且有更好的扩展性(提供更多的子类)
4,使用顺序
Lock > 同步代码块(已经进入方法体,分配了相应的资源)> 同步方法(在方法体之外)
1.16 线程协作,生产者消费者模式
1.16.1 线程通信
1,管程法:
package com.huanglk.syn;
//生产者 , 消费者 , 产品 , 缓冲区
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++) {
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;//编号
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() {
//判断能否消费
if (count == 0) {
//消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
2.信号灯法
package com.huanglk.syn;
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("节目AAA");
}else {
this.tv.play("节目BBB");
}
}
}
}
class Watcher extends Thread{
TV tv;
public Watcher( TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0;i<20;i++){
this.tv.watch();
}
}
}
class TV{
// 演员表演,观众等待
// 观众观看,演员等待
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;
}
}
1.17 线程池
1,背景:线程经常创建和销毁,使用资源较大,对性能影响较大
2,思路:提前创建号多个线程,放入线程池中,使用时直接获取,使用完后放回池中,避免频繁创建销毁。类似生活中的公交车
3,好处:提高响应速度(减少创建线程的时间)
降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
便于管理线程
4,常用ThreadPoolExecutor,
package com.huanglk.syn;
import java.util.concurrent.*;
public class TestPool {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) {
//使用ExecutorService
//1,创建服务,创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//2,执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2,关闭链接
service.shutdown();
//使用ThreadPoolExecutor
//使用阿里巴巴推荐的创建线程池的方式
//通过ThreadPoolExecutor构造函数自定义参数创建
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
//执行
executor.execute(new MyThread());
executor.execute(new MyThread());
executor.execute(new MyThread());
executor.execute(new MyThread());
executor.execute(new MyThread());
executor.execute(new MyThread());
executor.execute(new MyThread());
//2,关闭链接
executor.shutdown();
// while (!executor.isTerminated()) {
// }
// System.out.println("Finished all threads");
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}