zoukankan      html  css  js  c++  java
  • 多线程

    一、多线程

    生命周期
    1、新建: 使用 new 关键字和 Thread 类或其子类建立一个线程对象后,该线程对象就处于新建状态。它保持这个状态直到程序 start() 这个线程
    2、就绪: 当线程对象调用了start()方法之后,该线程就进入就绪状态。就绪状态的线程处于就绪队列中,要等待JVM里线程调度器的调度。
    3、运行: 如果就绪状态的线程获取 CPU 资源,就可以执行 run(),此时线程便处于运行状态。处于运行状态的线程最为复杂,它可以变为阻塞状态、就绪状态和死亡状态。
    4、阻塞: 执行了sleep(睡眠)、suspend(挂起)等方法,失去所占用资源之后,该线程就从运行状态进入阻塞状态。在睡眠时间已到或获得设备资源后可以重新进入就绪状态。 可以分为三种:
    等待阻塞,运行状态中的线程执行 wait() 方法,使线程进入到等待阻塞状态。
    同步阻塞,线程在获取 synchronized 同步锁失败(因为同步锁被其他线程占用)
    其他阻塞,通过调用线程的 sleep() 或 join() 发出了 I/O 请求时,线程就会进入到阻塞状态。当sleep() 状态超时,join() 等待线程终止或超时,或者 I/O 处理完毕,线程重新转入就绪状态
    5、死亡: 一个运行状态的线程完成任务或者其他终止条件发生时,该线程就切换到终止状态。

    线程的优先级
    1、线程优先级用于系统确定线程的调度顺序。
    2、高优先级的线程对程序更重要,且在低优先级的线程之前分配处理器资源。但是,线程优先级不能保证线程执行的顺序,而且非常依赖于平台。
    3、取值范围是 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY ),默认情况 5(NORM_PRIORITY)

    实现 Runnable 接口

    import java.awt.*;
    
    class RunnableDemo implements Runnable {
        private Thread t;
        private String threadName;
    
        RunnableDemo(String name) {
            threadName = name;
            System.out.println("Creating " + threadName);
        }
    
        public void run() {
            try {
                for (int i = 4; i > 0; i--) {
                    System.out.println("Thread: " + threadName + ", " + i);
                    Thread.sleep(5); // 让线程睡眠一会
                }
            } catch (InterruptedException e) {
                System.out.println("Thread " + threadName + " interrupted.");
            }
            System.out.println("Thread " + threadName + " exiting.");
        }
    
        public void start() {
            System.out.println("Starting " + threadName);
            if (t == null) {
                t = new Thread(this, threadName);
                t.start();//通过native start0再调用run,只不过代码看不到
            }
        }
    }
    
    public class 多线程 {
    
        public static void main(String args[]) throws AWTException {
            Robot r = new Robot();
    
            RunnableDemo R1 = new RunnableDemo("Thread-1");
            R1.start();
    
            System.out.println("延时开始");
            r.delay(10);
    
            RunnableDemo R2 = new RunnableDemo("Thread-2");
            R2.start();
        }
    }

     通过继承Thread来创建线程

    class ThreadDemo extends Thread {
        private String threadName;
    
        ThreadDemo(String name) {
            threadName = name;
            System.out.println("Creating " + threadName);
        }
    
        public void run() {
            try {
                for (int i = 4; i > 0; i--) {
                    System.out.println("Thread: " + threadName + ", " + i);
                    Thread.sleep(50); // 让线程睡眠一会
                }
            } catch (InterruptedException e) {
                System.out.println("Thread " + threadName + " interrupted.");
            }
            System.out.println("Thread " + threadName + " exiting.");
        }
    }
    
    public class 多线程2 {
        public static void main(String args[]) {
            Thread T3 = new ThreadDemo("Thread-3");
            T3.start();
        }
    }

    通过 Callable 和 Future 创建线程

    1. 创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。
    2. 创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。
    3. 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。
    4. 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。

    创建线程的三种方式的对比
    1. 采用实现 Runnable、Callable 接口的方式创建多线程时,线程类只是实现了 Runnable 接口或 Callable 接口,还可以继承其他类。
    2. 使用继承 Thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用 this 即可获得当前线程。

    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    public class CallableThreadTest implements Callable<Integer> {
        public static void main(String[] args) {
            CallableThreadTest ctt = new CallableThreadTest();
            FutureTask<Integer> ft = new FutureTask<>(ctt);
    
            for (int i = 0; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
                if (i == 10) {
                    Thread a= new Thread(ft, "有返回值的线程");
                    a.start();
                    System.out.println(a.getName() + " ====" );
    
                }
            }
            try {
                System.out.println("子线程的返回值:" + ft.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            return i;
        }
    }
    测试进阶轨迹
  • 相关阅读:
    nodejs微服务
    node 操作文件流 fs 同步与异步 流式文件的写入与读取
    node判断文件目录是否存在
    Nodejs 使用 Chrome DevTools 调试 --inspect-brk
    使用ovftool工具实现exsi上主机的导入导出
    redis哨兵
    LVS+Nginx
    nginx的proxy代理缓存
    flanneld启动报错Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
    flanneld启动报错Failed to create SubnetManager: parse first path segment in URL cannot contain colon
  • 原文地址:https://www.cnblogs.com/yinwenbin/p/15067453.html
Copyright © 2011-2022 走看看