多线程(自用)【未完成】

多线程

目录

线程创建

Thread

    public class ThreadTest {
        public static void main(String[] args) {
            TestThread testThread = new TestThread();
            testThread.start();

            for (int i = 0; i < 200; i++) {
                System.out.println("main");
            }

        }
    }
    class TestThread extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("MyThread running");
            }

        }
    }

Runnable

    public class RunnableTest {
        public static void main(String[] args) {
            TestRunnable testRunnable = new TestRunnable();

            new Thread(testRunnable).start();

            for (int i = 0; i < 200; i++) {
                System.out.println("main");
            }


        }


    }

    class TestRunnable implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("MyThread running");
            }
        }
    }

Callable

    public class CallaleTest {
        public static void main(String[] args) {
            TestCallable testCallable = new TestCallable();

            //创建执行服务
            ExecutorService executorService = Executors.newFixedThreadPool(1);

            //提交执行
            Future<String> r=executorService.submit(testCallable);

            for (int i = 0; i < 100; i++) {
                System.out.println("main");
            }

            //获取结果
            try {
                String result = r.get();
                System.out.println(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            //关闭服务
            executorService.shutdown();


        }
    }

    class TestCallable implements Callable {

        @Override
        public String call() throws Exception {
            for (int i = 0; i < 100; i++) {
                System.out.println("MyThread running");
            }
            return "done";
        }
    }

lambda表达式

  • 演化版本

    //定义函数式接口
    interface TestLambda {
        void lambda();
    }
    
    //1. 外部实现类
    class OuterClass implements TestLambda {
        @Override
        public void lambda() {
            System.out.println("OuterClass");
        }
    }
    
    public class LambdaTest {
    
        //2. 静态内部类
        static class StaticInterClass implements TestLambda {
            @Override
            public void lambda() {
                System.out.println("StaticInterClass");
            }
        }
    
        public static void main(String[] args) {
    
            //3. 局部内部类
            class LocalInterClass implements TestLambda {
                @Override
                public void lambda() {
                    System.out.println("LocalInterClass");
                }
            }
    
    
            TestLambda outerClass = new OuterClass();
            outerClass.lambda();
    
            TestLambda staticInterClass = new StaticInterClass();
            staticInterClass.lambda();
    
            TestLambda localInterClass = new LocalInterClass();
            localInterClass.lambda();
    
            //4. 匿名内部类
            TestLambda anonymousInterClass = new TestLambda() {
                @Override
                public void lambda() {
                    System.out.println("AnonymousInterClass");
                }
            };
            anonymousInterClass.lambda();
    
            //5. lambda简化
            TestLambda lambdaInterClass = () -> {
                System.out.println("lambdaInterClass");
            };
            lambdaInterClass.lambda();
    
        }
    }
    
    
  • Runnable版

    //外部实现类
    class OuterRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("OuterClass");
        }
    }
    public class RunnableLambdaTest {
        //静态内部类
        static class StaticRunnable implements Runnable{
            @Override
            public void run() {
                System.out.println("StaticRunnableClass");
            }
        }
    
        public static void main(String[] args) {
            //本地内部类
            class LocalRunnable implements Runnable{
                @Override
                public void run() {
                    System.out.println("LocalRunnable");
                }
            }
    
            OuterRunnable outerRunnable = new OuterRunnable();
    
            StaticRunnable staticRunnable = new StaticRunnable();
    
            LocalRunnable localRunnable = new LocalRunnable();
    
            //匿名内部类
            Runnable anonymousRunnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("anonymousRunnable");
                }
            };
    
            //lambda表达式
            Runnable lambdaRunnable =()->{
                System.out.println("lambdaRunnable");
            };
    
            ThreadPoolExecutor pool = new ThreadPoolExecutor(
                    5,
                    5,
                    3,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(5),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.CallerRunsPolicy()
            );
    
            try {
                pool.execute(outerRunnable);
                pool.execute(staticRunnable);
                pool.execute(localRunnable);
                pool.execute(anonymousRunnable);
                pool.execute(lambdaRunnable);
            } finally {
                pool.shutdown();
            }
    
        }
    }
    

线程的停止,休眠sleep,礼让yield,强制执行(插队)join

线程状态

  1. 创建
  2. 就绪
  3. 阻塞
  4. 运行
  5. 死亡

停止

  • 让线程正常停止,使用固定次数循/标志位
  • 不使用stop、destroy等方式停止线程

sleep 休眠

InterruptedException

  • sleep指定线程阻塞毫秒数
  • sleep结束后线程进入就绪状态
  • sleep可模拟网络延时
  • sleep不会释放锁

yield 礼让

  • 让当前正在执行的线程暂停但不阻塞
  • 让线程从运行状态转为就绪状态
  • 让cpu重新调度

join 强制执行

  • 合并线程,待线程执行完后,再执行其他线程,其他线程阻塞
  • 类比插队

线程的状态,优先级,守护线程deamon

State 状态

  • NEW 尚未启动的线程
  • RUNNABLE 运行中的
  • BLOCKED 阻塞
  • WAITING 等待
  • TIME_WAITING 超时等待
  • TERMINATED 终止

线程优先级

  • 优先级用数字表示,1~10
    • Thread.MIN_PRIORITY=1
    • Thread.NORM_PRIORITY=5
    • Thread.MAX_PRIORITY=10
  • 获取/修改优先级
    • getPriority()
    • setPriority(int xxx)

守护线程

记录操作日,监控内存,垃圾回收(GC)

  • setDaemon(true/false)

死锁

  1. 互斥条件

    一个资源每次只能被一个进程使用。

  2. 请求与保持条件

    一个进程因请求资源而阻塞时,对已获得的资源保持不放。

  3. 不剥夺条件

    进程已获得的资源,在末使用完之前,不能强行剥夺。

  4. 循环等待条件

    若干进程之间形成一种头尾相接的循环等待资源关系.
    read.MAX_PRIORITY=10

  • 获取/修改优先级
    • getPriority()
    • setPriority(int xxx)

守护线程

记录操作日,监控内存,垃圾回收(GC)

  • setDaemon(true/false)

死锁

  1. 互斥条件

    一个资源每次只能被一个进程使用。

  2. 请求与保持条件

    一个进程因请求资源而阻塞时,对已获得的资源保持不放。

  3. 不剥夺条件

    进程已获得的资源,在末使用完之前,不能强行剥夺。

  4. 循环等待条件

    若干进程之间形成一种头尾相接的循环等待资源关系.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值