java.基础(多线程)

JAVA 多线程

Spring静态代理

真实对象和代理对象都要实现同一个接口

代理对象要代理真实角色

interface Marry{
    public void HappyMarry();
}


class You implements Marry{


    @Override
    public void HappyMarry() {
        System.out.println("我结婚了");
    }
}

class StaticProxy implements Marry{
    private Marry marry;

    public StaticProxy(Marry marry){
        this.marry = marry;
    }

    @Override
    public void HappyMarry() {
        before();
        this.marry.HappyMarry();
        after();
    }

    private void after() {
        System.out.println("婚后。");
    }

    private void before() {
        System.out.println("婚前准备");
    }
}

class start {
    public static void main(String[] args) {
        StaticProxy staticProxy = new StaticProxy(new You());
        staticProxy.HappyMarry();
    }
}

Lambda

  • 任何接口 ,如果只包含唯一一个抽象方法,那么他就是函数式接口

  • 函数式接口可以使用lambda表达式

线程状态

创建状态–> 就绪状态–>阻塞状态–>运行状态–>死亡状态

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BAaawyNj-1646992674535)(C:\Users\enjoy\AppData\Roaming\Typora\typora-user-images\image-20220223153750058.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WfV7gPQg-1646992674536)(C:\Users\enjoy\AppData\Roaming\Typora\typora-user-images\image-20220223153838487.png)]

线程停止

1、建议线程正常停止-->利用次数,不建议死循环
2、建议使用标志位-->设置一个标志位
3、不要使用stop或者destory等过时或者JDK不建议使用得方法
//当主线程到5000次时  设置停止
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 < 10000; i++) {
            System.out.println("主线程正在执行第"+i+"次");
            if (i==5000) {
                testStop.stop();
                System.out.println("线程该停止了");
            }
        }
    }
}

线程休眠

  • sleep(时间)指定当前线程阻塞的毫秒数
  • sleep 存在异常InterruptedException;
  • sleep时间打到后线程进入就绪状态;
  • sleep 可以模拟网络延迟,倒计时等;
  • 每一个对象都有锁 ,sleep 不会释放锁;
//倒计时实现  10-0 
public class testSleep {
    public static void main(String[] args) throws InterruptedException {
        tenDown();
    }
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while(num >=0 ){
            System.out.println(num--);
            Thread.sleep(1000);
        }
    }
}

小记 时间格式化(格式化当前系统时间)

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()))

线程礼让(yield)

  • 礼让进程,让当前执行的线程停止,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让cpu重新调度,礼让不一定成功,看cpu心情
public class testYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"线程1").start();
        new Thread(myYield,"线程2").start();

    }
}
class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();//线程礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}
//执行结果如下 则是礼让失败的状况

线程1线程开始执行
线程1线程停止执行
线程2线程开始执行
线程2线程停止执行

线程Join (插队)

  • Join 合并线程,等待此线程执行完成后,再执行其他线程,其他线程阻塞
  • 可以想象成插队
//测试join方法  //想像为插队
//当i<200 时   main线程与新线程抢夺cpu交替执行   当i=200 时 执行
//join操作  mian线程等待join线程执行完毕后继续执行 
public class testJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("我来插队了"+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++) {
            System.out.println("main 线程"+ i);
            if (i==200){
                thread.join();
            }
        }
    }
}

观测线程状态

  • Thread.State

    • NEW

      尚未启动的线程处于此状态

    • RUNNABLE

      在Java虚拟机中执行的线程处于此状态

    • BLOCKED

      被组测等待监视器锁定的线程处于此状态

    • WAITING

      正在等待另一个线程执行特定东站的线程处于此状态

    • TIMED_WAITING

      正在等待另一个线程执行动作打到指定等待时间的线程处于此状态

    • TERMINATED

      已退出的线程处于此状态

  • 死亡之后的线程不能重新启动

线程优先级

  • Java 提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
  • 线程优先级用数字表示,范围从1~10 (超出范围会报错)
    • Thread.MIN_PRIORITY = 1 (优先级最低)
    • Thread.MAX_PRIORITY = 10 (优先级最高)
    • Thread.NORM_PRIORITY = 5 (默认优先级)
  • 使用一下方式改变活获取优先级
    • getPriority() setPriority(int xxx)
public class testPriority{
    public static void main(String[] args) {
        //主线程优先级
        System.out.println(Thread.currentThread().getName()+Thread.currentThread().getPriority());
        Mypriority mypriority = new Mypriority();
        Thread thread1 = new Thread(mypriority);
        Thread thread2 = new Thread(mypriority);
        Thread thread3 = new Thread(mypriority);
        Thread thread4 = new Thread(mypriority);
        Thread thread5 = new Thread(mypriority);
        Thread thread6 = new Thread(mypriority);
        Thread thread7 = new Thread(mypriority);

        thread1.setPriority(1);
        thread1.start();

        thread2.setPriority(2);
        thread2.start();

        thread3.setPriority(3);
        thread3.start();

        thread4.setPriority(4);
        thread4.start();

        thread5.setPriority(5);
        thread5.start();

        thread6.setPriority(6);
        thread6.start();

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

守护线程(daemon)

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

  • 虚拟机必须确保用户线程执行完毕

  • 虚拟机不用等待守护线程执行完毕

  • 如 后台记录操作日志,监控内存,垃圾回收等

public class testDeamon {
    public static void main(String[] args) {
        God god = new God();
        Thread thread = new Thread(god);
        //线程启动前  设置线程为守护线程  当主线程结束时  守护线程随之结束 
        //除设置为守护线程外  其余为正常线程  主线程
        thread.setDaemon(true);  
        thread.start();

        You you = new You();
        Thread thread1 = new Thread(you);
        thread1.start();
    }
}


class God implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("I'm God ,so ..我永生");
        }
    }
}

class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("我还活着");
        }
        System.out.println("I'm die");
    }
}

线程同步

当多个线程操作同一个资源

  • 由于同意进程的多个线程共享同一块存储空间。再带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制(synchronized),当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可 存在一下问题
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起
    • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题

死锁问题

  • 产生死锁的必要条件:

    • 互斥条件:一个资源每次只能呗一个进程使用
    • 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不妨
    • 不剥夺条件:进程已获得资源,在未使用完之前,不能强行剥夺
    • 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系

    上面列出死锁的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁发生

Lock锁

  • Lock是显示锁(手动开启和关闭锁,别忘了关闭锁)Synchronized 是隐式锁,出了作用域自动释放
  • Lock只有代码块锁,synchronized 有代码块锁和方法锁
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多子类)
  • 优先使用顺序:
    • Lock > 同步代码块(已经进入了方法体,分配了相应资源)> 同步方法(在方法体之外)
//使用Lock手动加锁

import java.util.concurrent.locks.ReentrantLock;

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


        new Thread(testLock).start();
        new Thread(testLock).start();
        new Thread(testLock).start();

    }

}
public class testLock implements Runnable{
    int ticketNums = 10;

    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 {
                    break;
                }
            }finally {
                lock.unlock();//解锁
            }
        }
    }
}

线程协作(生产者消费者)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lCxZFSU2-1646992674538)(C:\Users\enjoy\AppData\Roaming\Typora\typora-user-images\image-20220226180027138.png)]

  • 解决方式一 (并发写作模型 生产者消费者模式 ---->管理法)

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-h2OgHoqw-1646992674539)(C:\Users\enjoy\AppData\Roaming\Typora\typora-user-images\image-20220226180049043.png)]

 package 多线程;
 
 
 //利用缓冲区解决:管程法
 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 sysContainer){
         this.container = sysContainer;
     }
 
     @Override
     public void run() {
         for (int i = 0; i < 100; i++) {
             System.out.println("生产了"+(i+1)+"只鸡");
             container.push(new Chicken(i));
         }
     }
 }
 
 
 class consumer extends Thread{
     SynContainer container;
     public consumer(SynContainer sysContainer){
         this.container = sysContainer;
     }
 
     @Override
     public void run() {
         for (int i = 0; i < 100; i++) {
             System.out.println("消费了"+(container.pop().id+1)+"只鸡");
         }
     }
 }
 
 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) {
         while (count == chickens.length) {
             try {
                 //等待
                 this.wait();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         chickens[count] = chicken;
         count++;
         //通知消费者消费
         this.notifyAll();
     }
     //消费者
     public synchronized Chicken pop() {
         while (count == 0) {
             try {
                 this.wait();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         count--;
         Chicken chicken = chickens[count];
         //通知生产者生产
         this.notifyAll();
         return chicken;
     }
 }
  • 解决方法2:并发协作模型 信号灯法

    • 通过标志位判断状态
    package 多线程;
    
    public class testPc2 {
        public static void main(String[] args) {
            Tv tv = new Tv();
            new YanYuan(tv).start();
            new GuanZhong(tv).start();
        }
    }
    
    class YanYuan extends Thread{
        Tv tv;
        public YanYuan(Tv tv){
            this.tv = tv;
        }
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                if (i%2==0){
                    try {
                        this.tv.BiaoYan("大本营");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        this.tv.BiaoYan("抖音");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    class GuanZhong extends Thread{
        Tv tv;
    
        public GuanZhong(Tv tv){
            this.tv = tv;
        }
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                try {
                    tv.GuanKan();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    class Tv{
        //if true  需要表演
        //else 需要观看
        boolean flag = true;
        String TvName;
    
        public synchronized void BiaoYan(String tvName) throws InterruptedException {
            while (!flag){
                this.wait();
            }
            System.out.println("演员正在上映"+tvName+"节目");
            this.notifyAll();
            this.TvName = tvName;
            this.flag = !this.flag;
    
        }
    
        public synchronized void GuanKan() throws InterruptedException {
            while (flag){
                this.wait();
            }
                System.out.println("观众正在观看"+this.TvName+"节目");
                this.flag = !this.flag;
                this.notifyAll();
    
        }
    }
    

线程池




import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class pool {
    public static void main(String[] args) {
    //声明线程池对象及大小
        ExecutorService service = Executors.newFixedThreadPool(10);
	//执行
        service.execute(new testPool());
        service.execute(new testPool());
        service.execute(new testPool());
        service.execute(new testPool());
        service.execute(new testPool());
	//关闭
        service.shutdown();
    }
}
class testPool implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值