线程状态
五大状态
- 创建状态:Thread thread = new Thread(); 线程对象一旦创建就进入了新生状态。
- 就绪状态:当调用start()方法时,进入就绪状态,但不代表立即调度执行(等待cpu调度)。
- 运行状态:进入运行状态,线程才真正执行线程体的代码块。
- 阻塞状态:当调用sleep,wait或同步锁时,线程进入阻塞状态,就是代码不往下执行,阻塞解除后进入就绪状态,等待cpu调度。
- 死亡状态:线程中断或者结束,进入死亡状态,不能再次启动。
停止线程
停止线程:不推荐使用jdk的方法(已废弃),建议使用一个标志位进行终止变量,当fiag=false时,则终止线程进行。
package com.thread.stop;
//停止线程
//建议线程正常停止 利用次数 不建议死循环
//建议使用标志位
//不要使用stop或者destory等
public class TestStop implements Runnable{
//设置标志位
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("线程停止了");
}
}
}
}
线程休眠
sleep(时间)指定当前线程阻塞的毫秒数。
sleep存在异常interrupteException。
sleep时间到达后线程进入就绪状态。
sleep可以模拟网络延时,倒计时等。
每一个对象都有一个锁,sleep不会释放锁。
package com.thread.lesson02;
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) throws Exception {
test();
}
public static void test() throws Exception {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
public class TestSleep3 {
public static void main(String[] args) throws Exception {
//打印系统当前时间
Date time = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
time = new Date(System.currentTimeMillis());//更新当前系统时间
}
}
线程礼让
线程礼让(yield):让当前正在执行的线程暂停,但不阻塞。将线程从运行状态转化为就绪状态,让cpu重新调度。
package com.thread.thread;
//线程礼让 礼让不一定成功
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()+"线程结束执行");
}
}
线程合并
Join合并线程,待此线程执行完毕后,再执行其他线程,其他线程阻塞。
package com.thread.thread;
//join方法 类似插队
public class TestJoin 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 Exception {
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.thread.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);
}
}
}
线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级来决定应该调度哪个线程来执行。
线程的优先级(priority)用数字表示,范围从1–10。使用getPriority()和setPwriority()来获取,改变优先级。
线程优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,主要看cpu的调度(优先级低的也有可能先执行)。
优先级设定在线程启动之前。线程的默认优先级为5。
package com.thread.thread;
//测试线程的优先级
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);
//先设置优先级再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(8);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}
守护线程
线程分为用户线程和守护(daemon)线程。
虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕。如操作日志,监控内存,垃圾回收等。
package com.thread.thread;
//测试守护线程
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 < 100; i++) {
System.out.println("活着!");
}
System.out.println("-----goodbye world!");
}
}
线程同步
使用场景:出现并发,多个线程操作同一个资源。
处理多线程问题时,多个线程访问同一个对象,并且某个线程还想修改这个对象,这个时候我们就需要线程同步,线程同步就是一种等待机制,多个需要同时访问此对象的线程进入对象的等待池,形成队列,等待前面线程使用完毕,下一个线程再使用。
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突的问题,为了保证数据在方法中被访问的正确性,在访问时加入锁机制(synchronized),当一个线程获得对象的排它锁,独占资源,其他线程必须等待 ,事后释放锁。
存在的问题:一个线程有锁会导致其它所有需要此锁的线程挂起;在多线程竞争下,加锁和释放锁会导致比较多的上下文切换和调度延时,引起性能问题;如果一个优先级高的等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。
不安全案例:
买票
package com.thread.thread;
//买票
public class UnSafeTicket{
public static void main(String[] args) {
ByTicket station = new ByTicket();
new Thread(station,"小周").start();
new Thread(station,"小张").start();
new Thread(station,"小秦").start();
}
class ByTicket implements Runnable{
private int ticketnums = 10;
boolean flag = true;
@Override
public void run() {
//标志位
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketnums<=0){
flag = false;
return;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketnums--+"张票");
}
}
银行取钱
package com.thread.thread;
//不安全的取钱
public class UnSafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "基金");
Drawing you = new Drawing(account,50,"你");
Drawing girlFruend = new Drawing(account,100,"girlFriend");
you.start();
girlFruend.start();
}
}
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行模拟取款
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() {
//判断余额
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);
//Thread.currentThread().getName()这里等价于this.getName()
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
不安全的集合
package com.thread.thread;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合 list
public class UnSafeList throws Exception{
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
同步方法及同步块
由于我们可以通过priviate关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,即synchronized关键字。它有两种用法:synchronized方法和synchronized代码块。
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
注意:将一个大的方法声明为synchronized会影响效率。
同步方法:public synchronized void method(int args){…}
同步块:synchronized(obj){…}
obj称之为同步监视器,obj可以是任意对象,但是推荐使用共享资源作为同步监视器。同步方法中无需指定同步监视器,因为同步方法中同步监视器就是this,就是这个对象本身。
同步监视器的执行过程:
- 第一个程序访问,锁定同步监视器,执行其中代码。
- 第二个程序访问,发现同步监视器被锁定,无法访问。
- 第一个线程访问完毕:解锁同步监视器。
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问。
银行取钱加synchronized
package com.thread.thread;
//不安全的取钱
public class UnSafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "基金");
Drawing you = new Drawing(account,50,"你");
Drawing girlFruend = new Drawing(account,100,"girlFriend");
you.start();
girlFruend.start();
}
}
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行模拟取款
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);
//Thread.currentThread().getName()这里等价于this.getName()
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
}
集合加synchronized
package com.thread.thread;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合 list
public class UnSafeList {
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
死锁
死锁:多个线程各自占有一些公共资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情况,某一个同步块同时拥有“两个以上对象的锁”时,就会发生死锁的问题。
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用。
- 请求与保持条件:一个进程因请求资源而阻塞时,对方获得的资源保持不放。
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
- 循环等待条件:若干资源之间形成一种头尾相接的循环等待资源的关系。
只要破坏上面任意一个或者多个条件就能避免死锁的发生。
以下一个代码块中有两个对象的锁会产生死锁(将其中一个锁放到代码块外即可避免死锁)
package com.thread.thread;
//死锁 多个线程互相抱着对方所需的资源,形成死锁
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"ZZ");
Makeup g2 = new Makeup(1,"RR");
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.girlName+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
}
Lock(锁)
从JDK5.0开始,Javat提供了更强大的线程同步机制——通过显是定义同步锁对象来实现同步,同步锁使用lock对象充当。
Java.util.concurrent.locks. Lock接口是控制多个线程对共享资源进行访问的工具;锁提供了对共享资源的独占访问,每次只能由一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
ReentrantLock(可重入锁)类中实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁,释放锁。
package com.thread.thread;
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 ticketunms = 10;
//定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
lock.lock();//加锁
try{
if (ticketunms<=0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketunms--);
}else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}
synchronized和Lock的区别:
- Lock式显式锁(手动开启和关闭锁 ),synchronized是隐式锁,出了作用域自动释放。
- Lock只有代码块锁,synchronized有代码块锁和方法锁。
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且拥有更好的拓展性(提供更多的子类)。
- 优先使用顺序:Lock>同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体外)
生产者和消费者
生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
对于生产者,没有生产产品之前,要通知消费者等待,而生产了产品之后,需要通知消费者马上消费。
对于消费者,在消费之后,要通知消费者已经结束消费,需要胜场新的产品以供消费。
在生产者和消费者问题中,仅有synchronized是不够的,synchronized可阻止并发更新同一个资源,实现了同步。synchronized不能用来实现不同线程之间的消息传递(通信)。
解决线程通信问题的几个方法(均是object类的方法,都只能在同步方法或同步代码块中使用,否则会抛出异常):
- wait():表示线程一直等待,直到其它线程通知,与sleep不同,会释放锁。
- wait(long timeout:指定等待的毫秒数。
- notify():唤醒一个处于等待的线程。
- notifyAll():唤醒同一个对象上所有调用wait()的线程,优先级别搞得优先调度。
管程法
并发协作模型“生产者/消费者模式”—>管程法
- 生产者:负责生成数据的模块(可能是方法,对象,进程,线程)。
- 消费者:负责处理数据的模块(可能是方法,对象,进程,线程)。
- 缓冲区:消费者不能直接使用生产者的数据,它们之间有个缓冲区。
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。
package com.thread.thread;
//测试生产者消费者模型-->利用缓冲区解决:管程法
//生产者 消费者 产品 缓冲区
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[] chinken = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了等待消费者消费
if (count==chinken.length){
//需要通知消费者消费 生产等待
try{
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满就放入产品
chinken[count]=chicken;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count==0){
//等待生产者生产
try{
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chinken[count];
//通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法
package com.thread.thread;
//测试信号灯法 标志位解决
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 < 24; 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 < 24; i++) {
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.notify();
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;
}
}
线程池
经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能的影响特别大。
线程池:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建与销毁,实现重复利用。
优点:
- 提高响应速度(减少创建新线程的时间)
- 降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
- 便于线程管理
- corePoolSize:核心池大小
- maximumPoolSize:最大核心数
- keepAlive Time:线程没有任务时最多保持多长时间后终止
ExecutorService:真正的线程池接口;常见子类ThreadPoolExecutor。
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable。
- Futuresubmit(Callable task):执行任务,有返回值,一般用来执行Callable。
- void shutdown():关闭连接池。
Execoturs:工具类,线程池的工厂类,用于创建并返回不同类型的线程池。
package com.thread.thread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//创建线程池 参数线程为池的大小
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());
}
}