• Java线程基础学习笔记


    最近一直在跟着B站韩顺平老师的《零基础快速学Java》视频教程学习Java基础知识,教程地址——https://www.bilibili.com/video/BV1fh411y7R8?spm_id_from=333.999.0.0, 目前已经学到了程序进程线程基础部分,在学习过程中做了一些相关的学习笔记和心得,分享在博客,就当做是基础强化了,哈哈哈。

    线程基础

    1.线程介绍

    1.1进程

    进程是指运行中的程序,操作系统为启动的程序分配内存空间;

    进程是程序的一次执行过程,或是一个正在运行的程序。是一个动态的过程:有它自己的产生、存在和消亡的过程

    1.2线程

    线程由进程创建,是进程的一个实体

    一个进程可以拥有多个线程

    1.3并发与并行

    并发:同一时刻,多个任务交替执行。单核CPU可以实现

    并行:同一时刻,多个任务同时执行。多核CPU可以实现

    2.线程使用

    2.1继承Thread创建线程

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/26 9:24
     * @Version 1.0
     *
     * 程序启动就开起了一个进程
     * 进入到main方法之后,就开启了一个主线程
     * 通过hello.start()开启了子线程Thread-0
     */
    public class thread  {
        public static void main(String[] args) throws InterruptedException {
            Hello hello = new Hello();//创建一个对象,当做线程来使用
            hello.start();//启动子线程Thread-0
    //        hello.run();//此时run方法是一个普通的方法,没有真正的启动一个线程,等run方法执行完毕之后,才回去执行之后的代码(阻塞)
            //当main线程启动一个子线程之后,主线程不会阻塞,会继续执行,子线程和主线程交替执行
            System.out.println("主线程"+Thread.currentThread().getName());//main
            for (int i = 0; i < 60 ; i++) {
                System.out.println("主线程 main 执行次数="+i);
                Thread.sleep(1000);//抛出异常
            }
        }
    }
    @SuppressWarnings({"all"})
    //当一个类继承了Thread方法,那么该类可以当做一个线程类了
    class Hello extends Thread{
    
        @Override
        public void run() {//重写run方法(该方法通过实现Runnable接口中的run方法),写上自己的业务逻辑
            int times = 0;
            while (true){
                System.out.println("Hello world "+(++times) + "子线程名称"+ Thread.currentThread().getName());
                //让线程休眠一秒
                try {//通过try Catch处理异常
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if (times == 80){
                    break;//当times等于80的时候,退出循环,此时线程也退出
                }
            }
        }
    }
    

    2.2多线程机制

    //上面的程序通过hello.start()方法来实现多线程,因为如果直接调用线程类里面的run方法的话,实现的就是一个主线程即main线程,而不是thread-0线程了,在底层,通过JVM来实现start方法,去启东一个子线程
    

    2.3实现Runnable接口创建线程

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/26 9:24
     * @Version 1.0
     *
     * 通过实现接口Runnable来创建线程
     */
    public class thread  {
        public static void main(String[] args) {
            Hello hello = new Hello();
    //        hello.start();//这里不能调用start方法
            Thread thread = new Thread(hello);//创建了一个Thread对象,把已经实现了Runnable接口的Hello对象放入Thread对象中
            thread.start();
        }
    }
    
    class Hello implements Runnable{
        @Override
        public void run() {
            int num = 0;
            while (true){
                System.out.println("hello"+(++num)+"     线程名称>>>"+Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if (num == 10){
                    break;
                }
            }
        }
    }
    

    2.4多个子线程案例

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/26 9:24
     * @Version 1.0
     *
     * 在main线程启动两个子线程
     */
    public class thread  {
        public static void main(String[] args) {
            Hello hello = new Hello();
            World world = new World();
            Thread thread1 = new Thread(hello);
            Thread thread2 = new Thread(world);
            thread1.start();
            thread2.start();
        }
    }
    
    class Hello implements Runnable{
        @Override
        public void run() {
            int num = 0;
            while (true){
                System.out.println("Hello "+(++num)+"线程名:"+Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if (num == 10){
                    break;
                }
            }
        }
    }
    
    class World implements Runnable{
        @Override
        public void run() {
            int num = 0;
            while (true){
                System.out.println("world "+(++num)+"线程名:"+Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if (num == 5){
                    break;
                }
            }
        }
    }
    

    2.5多线程售票问题

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/26 9:24
     * @Version 1.0
     *
     * 使用多线程模拟三个窗口同时售票100张
     */
    public class thread  {
        public static void main(String[] args) {
            //创建窗口
            SellTicket01 sellTicket01 = new SellTicket01();
            SellTicket01 sellTicket02 = new SellTicket01();
            SellTicket01 sellTicket03 = new SellTicket01();
            //出现票数超卖问题,可以通过Synchronized来解决该问题(线程的同步和互斥)
            sellTicket01.start();
            sellTicket02.start();
            sellTicket03.start();
        }
    }
    
    //使用继承Thread类创建线程
    class SellTicket01 extends Thread{
        private static int num = 100;//让多个线程共享这个票数
        @Override
        public void run() {
            while (true){
                if (num <= 0){
                    System.out.println("售票结束");
                    break;
                }
                //售票休眠50毫秒
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                System.out.println("窗口 "+Thread.currentThread().getName()+"售出一张票"
                + "剩余票数" +(--num)
                );
            }
        }
    }
    

    2.6通知线程退出

    线程完成之后自动退出

    代码条件执行完毕,线程自动退出,但是主线程退出之后,子线线程不一定退出

    通知线程退出

    通过使用变量来控制run方法退出的方式停止线程

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/31 15:28
     * @Version 1.0
     */
    public class thread_exit {
        public static void main(String[] args) throws InterruptedException {
            T t = new T();
            t.start();
    
            Thread.sleep(10000);
            //通过主线程控制子线程的终止,必须可以修改loop变量
            //修改loop为false之后,退出run方法>>>通知方式
            t.setLoop(false);
        }
    }
    class T extends Thread{
        //设置一个控制变量
        private boolean loop = true;
        @Override
        public void run() {
            int count = 0;
            while (loop){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hello world..."+(++count));
            }
        }
    
        public void setLoop(boolean loop) {
            this.loop = loop;
        }
    }
    

    3.线程方法

    3.1线程常用方法

    setName//设置线程名称,使之与参数name相同
    
    getName//返回该线程的名字
    
    start//使该线程开始执行;Java虚拟机底层调用该diaman线程的start0()方法
    
    run//调用线程对象run方法
    
    setPriority//更改线程的优先级
    
    getPriority//获取线程额优先级
    
    sleep//在指定的毫秒数内让当前正在执行的线程休眠(即暂停执行)
    
    interrupt//中断线程
    
    yield//线程的礼让。让出CPU,让其他线程执行,但礼让的时间不确定,所以不一定会礼让成功
    
    join//线程的插队。插队的线程一旦插队成功,则一定会先执行完插入的线程的所有的任务
    

    3.2线程中断

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/31 15:28
     * @Version 1.0
     */
    public class thread_exit {
        public static void main(String[] args) throws InterruptedException {
            T t = new T();
            t.setName("王帅");
            t.setPriority(Thread.MIN_PRIORITY);//最小的优先级
            t.start();//启动子线程
            System.out.println("线程:"+t.getName()+"优先级:"+t.getPriority());
    
            //主线程打印五个语句,然后就中断子线程的休眠
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println("Hello..."+i);
            }
    
            t.interrupt();//main 线程中断
            System.out.println(Thread.currentThread().getName()+"...中断");
        }
    }
    class T extends Thread{//自定义线程类
    
        @Override
        public void run() {
            while (true){
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+ "吃包子..." + i);
                }
                try {
                    System.out.println(T.currentThread().getName() + "休眠中...");
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    //当该线程执行到一个interrupt方法时,就会catch一个异常,可以加入自己的业务代码
                    //InterruptedException 捕获到一个中断异常
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName() + "被 interrupt");
                }
            }
        }
    }
    

    3.3线程插队

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/31 15:28
     * @Version 1.0
     */
    public class thread_exit {
        public static void main(String[] args) throws InterruptedException {
            T t = new T();
            t.start();//启动子线程
            //让子线程插队到main线程前面,这样,main线程就会等子线程执行完毕再执行
            //如果没有进行join,则主线程和子线程就会交替执行
            for (int i = 0; i <= 20 ; i++) {
                Thread.sleep(1000);
                System.out.println("主线程吃 "+ i +" 个包子");
                if (i == 5){
                    System.out.println("*****主线程吃了五个*****");
                    t.join();//插入线程,让子线程执行完毕
                }
            }
        }
    }
    
    class T extends Thread{//自定义线程类
    
        @Override
        public void run() {
            for (int i = 0; i <= 20; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程吃了 " + i +" 个包子");//输出子线程内容
            }
        }
    }
    

    3.4用户线程和守护线程

    用户线程

    也叫作工作线程,当线程的任务执行完或通知方式结束

    守护线程

    一般为工作线程服务,当所有的用户线程结束,守护线程自动结束,常见的守护线程——垃圾回收机制

    package thread;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/31 15:28
     * @Version 1.0
     */
    public class thread_exit {
        public static void main(String[] args) throws InterruptedException {
            T t = new T();
            //将t设置成守护线程,当main进程结束之后(即所有线程结束之后),t线程也自动结束
            t.setDaemon(true);
            t.start();//启动子线程
            for (int i = 0; i <= 10 ; i++) {
                Thread.sleep(1000);
                System.out.println("Hello");
            }
        }
    }
    
    class T extends Thread{//自定义线程类
    
        @Override
        public void run() {
            for ( ; ; ) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("World");
            }
        }
    }
    

    4.线程生命周期

    JDK中用Thread.State枚举表示了线程的几种状态
    
    NEW	尚未启动的线程
    
    RUNNABLE	在Java虚拟机中执行的线程
    
    BLOCKED	被阻塞等监视器锁定的线程
    
    WAITING	正在等待另一个线程执行特定动作的线程
    
    TIME_WAITING	正在等待另一个线程执行动作达到指定等待时间的线程
    
    TERMINATED	已退出的线程
    

    5.Synchronized(线程同步机制)

    在多线程编程,一些敏感数据不允许被多个线程同时访问,此时就使用同步访问技术,保证数据在任何时刻,最多有一个线程访问,以保证数据的完成性;

    当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作。

  • 相关阅读:
    R语言做文本挖掘 Part4文本分类
    在VS2005中使用原来的IIS调试Web程序(像VS2003一样)
    “提高一下dotnet程序的效率一”中关于exception的问题
    asp.net Cookies 转码的问题 中文丢失
    静态构造函数
    js在firefox中的问题
    模板引擎的一种实现
    .NET面试题,看看你的水平[转]
    转载 软件架构师应该具备的素质(Enterprise Solution Architects and Leadership)
    用正则表达式提取url中的Querystring参数
  • 原文地址:https://www.cnblogs.com/nanfengashuai/p/15264533.html
Copyright © 2020-2023  润新知