Java之多线程补充

线程停止

线程状态:创建、就绪、阻塞、执行、死亡

多个线程到就绪状态时统一听从cpu的调度运行

停止线程的2个方式

1.建议正常停止-->设置次数,不要陷入死循环

2.使用标志位

不要使用JDK中不建议或已经过时的方法

以下是标志位结束代码:

public class Demo implements Runnable{
    private boolean flag = true;
    @Override
    public void run() {
        int i=0;
        while (flag){
            System.out.println("第"+i+"次循环");
            i++;
        }
    }

    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(demo).start();

        for (int i = 0;i < 1000;i++){
            System.out.println("main第"+i+"次循环");
            if (i == 900){
                demo.stop();
                System.out.println("线程结束");
            }
        }
    }
}

线程休眠

Thread.sleep(毫秒);

注意:sleep存在异常,使用try..catch来获取异常并解决

sleep可以模拟网络延时

sleep到达时间后线程回归就绪状态

每一个对象都有一把锁,sleep不会释放锁

调用系统时间

首先需要导入java工具包 java.util.Date

获取当前时间new Date(System.currentTimeMillis())返回一个时间

如果要简化打印出的时间则需再导入包java.text.SimpleDateFormat

使用方法new SimpleDateFormat(显示方式).format(简化对象)

以下是打印时间的代码:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo{
    public static void main(String[] args) {
        int num = 0;
        Date startTime = new Date(System.currentTimeMillis());
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                System.out.println(startTime);
                startTime = new Date(System.currentTimeMillis());
                num++;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (num == 10){
                break;
            }
        }
    }
}

线程礼让

Thread.yield();

礼让不一定会成功,看cpu

本质是将线程从执行状态转为就绪状态

例子:

public class demo {
    public static void main(String[] args) {
        MyYield A = new MyYield();

        new Thread(A,"a").start();
        new Thread(A,"b").start();
    }
}
class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}

线程强制执行

可以理解为插队

语法:Thread.join()

将主线程转换为就绪状态,让插队的线程执行

插队例子:

public class Demo implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是大哥,让我插队!");
        }
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        Thread thread = new Thread(demo);
        thread.start();
        for (int i = 0; i < 300; i++) {
            if(i==150){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("排队中");
        }
    }
}

线程的状态

创建一个线程后可以利用:

引用变量.getState来获取一个返回的状态值

可以定义一个Thread.State类型的变量接收该返回值

线程一旦死亡就不能再次启动


线程的优先级

线程优先级范围(1~10)优先级(priority)越高越有可能先进行,还需要看cpu,优先级高不一定先执行

设置优先级方法:引用变量.setPriority(优先级)

例子:

public class Demo{
    public static void main(String[] args) {
        //打印主线程优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        MyPriority demo = new MyPriority();

        Thread t1 = new Thread(demo,"t1");
        Thread t2 = new Thread(demo,"t2");
        Thread t3 = new Thread(demo,"t3");
        Thread t4 = new Thread(demo,"t4");
        Thread t5 = new Thread(demo,"t5");
        Thread t6 = new Thread(demo,"t6");

        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(6);
        t4.start();

        t5.setPriority(7);
        t5.start();

        t6.setPriority(10);
        t6.start();
    }

}

class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

可以利用Thread.currentThread.getPriority();获取当前线程的优先级


守护(deamon)线程

线程分为用户线程守护线程

设置守护线程:

thread.setDeamon(false)    默认值为true,默认值是用户线程

当用户线程死亡时守护线程也会跟着结束

例子:

public class Demo {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        //默认是false表示是用户线程
        thread.setDaemon(true);
        thread.start();

        Thread thread1 = new Thread(you);
        thread1.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!===");
    }
}

线程同步机制

当多个线程同时操作一份资源时十分不安全会导致数据紊乱,所以出现了锁机制,所有线程呈队列形式排队访问资源

1.当一个线程进行访问时,线程就会拿到锁,其他线程必须等待,

2.这样会损失一定的性能

3.如果高优先级的在等待低优先级的线程释放锁,就会引起性能倒置


同步方法与同步块

使用关键字synchronized(同步)对方法进行修饰就可以让线程排队操作资源

修饰方法时锁住的是this,一个类中的方法被锁住时

当然这有一定的缺陷,当类1的数据在类2中的方法修改时,synchronized方法就无法奏效,所以有同步块的出现

语法:synchronized(锁住的对象){语法块}

同步方法案例:

public class Demo1 implements Runnable{
    private int tick = 10;

    @Override
    public synchronized void run() {
        while (true){
            if (tick<=0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+(tick--)+"张票");
        }
    }
    public static void main(String[] args) {
        Demo1 thedemo = new Demo1();

        new Thread(thedemo,"小明").start();
        new Thread(thedemo,"陈平安").start();
        new Thread(thedemo,"黄老师").start();
    }
}

同步块案例:

public class Demo2 {
    public static void main(String[] args) {
        Account account = new Account(100,"创业基金");

        Drawing You = new Drawing(account,50,"你");
        Drawing Company = new Drawing(account,100,"Company");

        You.start();
        Company.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) {
                throw new RuntimeException(e);
            }

            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(this.getName()+"手里的钱"+nowMoney);
        }
        }
}

CopyOnWriteArrayList

解决了线程数组的不安全性,也可以自己使用synchronized方法来解决

要导入包 java.util.concurrent.CopyOnWriteArrayList

import java.util.concurrent.CopyOnWriteArrayList;

public class Demo {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        System.out.println(list.size());
    }
}

死锁

当两个进程各持有一个锁,相互争夺对方手中的锁时,就形成了死锁

synchronized语法块没有结束时资源仍是被锁住的

以下案例可以说明,当把两个synchronized语法块放在一起时就形成了死锁

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 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() {
        makeup();
    }
    private void makeup(){
        if (choice == 0){
            synchronized (lipstick){
                System.out.println(this.girlName+"获得口红的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            synchronized (mirror){
                System.out.println(this.girlName+"获得镜子的锁");
            }
        }else {
            synchronized (mirror){
                System.out.println(this.girlName+"获得镜子的锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            synchronized (lipstick){
                System.out.println(this.girlName+"获得镜子的锁");
            }
        }
    }
}

Lock锁

lock锁是显式锁,需要主动开始和关闭,只有代码块锁

首先需要定义lock值        ReentrantLock   lock = new ReentrantLock();

加锁        lock.lock();

解锁        lock.unlock();

注意:

1.需要导入包 java.util.concurrent.locks.ReentrantLock

2.如果语句有异常,需要将解锁放入finally语句中

使用优先级:Lock>同步方法块>同步方法

ReentrantLock  可重复锁

synchronized是隐式锁,自动开始和关闭

例子:

import java.util.concurrent.locks.ReentrantLock;

public class Demo {
    public static void main(String[] args) {
        TestLock2 demo = new TestLock2();

        new Thread(demo).start();
        new Thread(demo).start();
        new Thread(demo).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 (Exception e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(ticketNums--);
                }else {
                    break;
                }
            } finally {
                //解锁
                lock.unlock();
            }

        }
    }
}

生产者消费者问题

管城法

涉及两个新方法 wait与notifAll

wait        让线程回到就绪状态并释放锁

notifAll        让线程回到执行状态

消费者和生产者之间实现通讯

当产品生产满库(缓冲区)时通知消费者消费,消费结束通知生产者可以开始生产

例子:

//生产者,消费者,产品,缓冲区
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) {
                throw new RuntimeException(e);
            }
            //通知消费者消费,生产等待
        }
        //如果没有满,我们就需要丢入产品
        chickens[count] = chicken;
        count++;
        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        if (count == 0){
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        //如果可以消费
        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) {
                throw new RuntimeException(e);
            }
        }
        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) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("观众观看了"+voice);
        //通知演员表演
        this.notifyAll();
        this.flag =!this.flag;
    }
}

线程池

经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大

要解决此问题有以下思路:提前创建很多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁、实现重复利用

优点:

1.提高响应速度(减少了创建新线程的时间)

2.降低资源消耗

3.便于线程管理

import java.util.concurrent.Executor;
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());
    }
}

  • 40
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值