多线程详解
核心概念
-
线程就是独立的执行路径
-
在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程, gc线程;
-
main()称之为主线程,为系统的入口,用于执行整个程序;
-
在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的。
-
对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;
-
线程会带来额外的开销,如cpu调度时间,并发控制开销。
-
每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
Thread类
线程开启不一定立即执行,由CPU调度执行
创建一个新的执行线程有两种方法。
-
一个是将一个类声明为
Thread
的子类。 这个子类应该重写run
类的方法Thread
。然后可以分配并启动子类的实例。 -
另一种方法来创建一个线程是声明实现类
Runnable
接口。 那个类然后实现了run
方法。 然后可以分配类的实例,在创建Thread
时作为参数传递,并启动。
然后,以下代码将创建一个线程并启动它运行:
PrimeRun p = new PrimeRun(143); new Thread(p).start();
方式一
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
public class One 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线程,主线程
//创建一个线程对象
One one = new One();
//调用start()方法开启线程
one.start();
for (int i = 0; i < 1000; i++) {
System.out.println("线程---" + i);
}
}
}
方式二
//创建线程方式二:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class Two implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 100; i++) {
System.out.println("数字---" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
Two two = new Two();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(two);
// thread.start();
new Thread(two).start();
for (int i = 0; i < 100; i++) {
System.out.println("线程--" + i);
}
}
}
并发任务
初识并发:
public class Ticket implements Runnable{
//票数
private int tickNums = 10;
@Override
public void run() {
while (true){
if (tickNums<=0){
break;
}
//模拟延迟
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + tickNums-- + "张票");
}
}
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket,"阿冰").start();
new Thread(ticket,"黄牛").start();
new Thread(ticket,"小泽").start();
}
}
在运行过程中会出现多个线程同时处理同一个资源的现象这个时候就需要并发。
处理并发任务的安全性:队列+锁。
龟兔赛跑例程
import java.util.Random;
//模拟龟兔赛跑
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
Random random = new Random();
int time = random.nextInt();
for (int i = 0; i <= 100; i++) {
//模拟兔子睡觉
if (Thread.currentThread().getName().equals("兔子") && i % time == 0) {
try {
Thread.sleep(1);
} 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;
}else {
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();
}
}
静态代理模式
public class StaticType {
public static void main(String[] args) {
WedingCompany wedingCompany = new WedingCompany(new You());
wedingCompany.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实对象,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("结婚了,超级开心!");
}
}
//代理角色,帮助你结婚
class WedingCompany implements Marry{
private Marry target; //代理谁-->真实目标
public WedingCompany(Marry target){
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void before() {
System.out.println("结婚之前");
}
private void after() {
System.out.println("结婚之后");
}
}
静态代理模式总结:
-
真实对象和代理对象都要实现同一个接口
-
代理对象要代理真实角色
好处:
-
代理对象可以做很多真实对象做不了的事情
-
真实对象专注做自己的事情
Lambda表达式
/*
推导Lambda表达式
*/
public class ClassLambda {
//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
public class TestLambda {
public static void main(String[] args) {
//lambda表示简化
Ilove ilove = (int a) -> {
System.out.println("I love you!" + a);
};
//简化1.参数类型
ilove = (a) -> {
System.out.println("1.I love you!" + a);
};
//简化2.简化括号
ilove = a -> {
System.out.println("2.I love you!" + a);
};
//简化3.简化花括号
ilove = a -> System.out.println("3.I love you!" + a);
ilove.love(520);
}
}
interface Ilove{
void love(int a);
}
总结:
-
lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。
-
前提是接口时函数式接口。
-
多个参数也可以去掉参数类型,要去掉都去掉,必须加上括号。
Stop方法:线程停止
//测试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 < 100; i++) {
System.out.println("main" + i);
if (i == 90){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了。");
}
}
}
}
Sleep方法:线程休眠
//计时器
public class TimeDown {
public static void main(String[] args) {
try {
Down();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void Down() throws InterruptedException {
int number = 10;
while (true) {
Thread.sleep(1000);
System.out.println(number--);
if (number <= 0)
break;
}
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
//打印当前系统时间
public class SystemTime {
public static void main(String[] args) {
Date startTime = new Date(System.currentTimeMillis()); //获取当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("YYYY/MM/DD\nHH:mm:ss\n").format(startTime));
startTime = new Date(System.currentTimeMillis()); //更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
每个对象都有一把锁,sleep方法不会释放锁。
Yield方法:线程礼让
-
礼让线程,让当前正在执行的线程暂停,但不阻塞
-
将线程从运行态转化为就绪态
-
让CPU重新调度,礼让不一定成功,看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() + "-->start");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "-->end");
}
}
Join方法:线程强制执行
-
Join合并线程,待线程执行完成后,在执行其他线程,其他线程阻塞
-
不建议使用,容易导致进程阻塞
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; 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 < 100; i++) {
if (i == 10){
thread.join();
}
System.out.println("main" + i);
}
}
}
线程的状态
线程可以处于以下状态之一:
NEW
尚未启动的线程处于此状态。RUNNABLE
在Java虚拟机中执行的线程处于此状态。BLOCKED
被阻塞等待监视器锁定的线程处于此状态。WAITING
正在等待另一个线程执行特定动作的线程处于此状态。TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。TERMINATED
已退出的线程处于此状态。
线程状态观测
//观测线程的状态
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} 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
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState(); //更新线程状态
System.out.println(state); //输出状态
}
}
}
守护优先级
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);
t1.start();
t2.setPriority(2);
t2.start();
t3.setPriority(6);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
"-->" +
Thread.currentThread().getPriority());
}
}
synchronized锁机制
-
由于我们可以通过 private 关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:
-
synchronized方法
-
synchronized块
-
//同步方法:
public synchronized void method(int args){} //synchronized默认锁的是this.
- synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
同步块
synchronized (Obj){}
-
Obj 称之为同步监视器
-
Obj 可以是任何对象(增删改的对象),但是推荐使用共享资源作为同步监视器
-
同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this ,就是
这个对象本身,或者是class [反射中讲解]
-
-
同步监视器的执行过程
-
第一个线程访问,锁定同步监视器,执行其中代码.
-
第二个线程访问,发现同步监视器被锁定, 无法访问.
-
第一个线程访问完毕,解锁同步监视器.
-
第二个线程访问, 发现同步监视器没有锁,然后锁定并访问
-
public class Bank {
public static void main(String[] args) {
Account account = new Account(100, "存钱");
GetMoney You = new GetMoney(account, 50, "我");
GetMoney Wife = new GetMoney(account, 100, "老婆");
Wife.start();
You.start();
}
}
//账户
class Account {
int SumMoney;
String name;
public Account(int sumMoney, String name) {
this.SumMoney = sumMoney;
this.name = name;
}
}
//取钱
class GetMoney extends Thread {
Account account; //账户
int TakeMoney; //取走了多少钱
int nowMoney; //手里有多少钱
public GetMoney(Account account, int TakeMoney, String name){
super(name);
this.account = account;
this.TakeMoney = TakeMoney;
}
//取钱
@Override
public synchronized void run(){
//锁的对象是账户
synchronized (account) {
//判断有没有钱
if (account.SumMoney - TakeMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够,没有取到钱");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额
account.SumMoney = account.SumMoney - TakeMoney;
//你手里的钱
nowMoney = nowMoney + TakeMoney;
System.out.println(this.getName() + "手里的钱:" + nowMoney);
System.out.println(account.name + "余额的钱还有" + account.SumMoney);
}
}
}
死锁
-
从JDK 5.0开始, Java提供了更强大的线程同步机制一通过显式定 义同步锁对象来实现同步。同步锁使用Lock对象充当
-
java.til.concurrent.locks.Lock接C是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有-个线程对Lock对象加锁,线程开始访问共享资源之前应先获得L ock对象
-
ReentrantLock类实现了Lock ,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
wantTicket buy = new wantTicket();
new Thread(buy,"a").start();
new Thread(buy,"b").start();
new Thread(buy,"c").start();
}
}
class wantTicket implements Runnable{
int TicketNum = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {//上锁
lock.lock();
if (TicketNum > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + TicketNum-- + "张票");
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
-
Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁, 出了作用域自动释放
-
Lock只有代码块锁,synchronized有代码块锁和方法锁
-
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
-
优先使用顺序:
- Lock >同步代码块(已经进入了方法体,分配了相应资源) >同步方法(在方法体之外)
生产者消费者问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待 ,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify | 唤醒一个处于等待状态的线程 |
notifyAll | 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 |
//测试:生产者消费者模型-->利用缓冲区:管程法
//生产者,消费者,产品,缓冲区
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();
}
}else {
//如果没有满,我们就需要丢入产品
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-->信号灯法,标志位解决
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;
}
}