博客
关于我
Java自学第8期——多线程
阅读量:423 次
发布时间:2019-03-06

本文共 5516 字,大约阅读时间需要 18 分钟。

多线程与线程安全问题

多线程概念

操作系统支持同时运行多个任务,每个任务通常是一个程序,所有运行中的程序称为进程。进程内部包含多个顺序执行流,每个流称为线程。多线程允许多个任务同时运行,特别是在多核CPU系统中,每个CPU都可以同时处理多个任务。

线程与进程的区别

  • 进程:资源分配的最小单位,程序执行过程的基本单位。每启动一个进程,系统分配地址空间和数据段。
  • 线程:程序执行的最小单位,一个进程至少有一个线程。多线程应用程序称为多线程程序。

线程调度

线程调度有两种方式:

  • 分时调度:轮流使用CPU,平均分配CPU时间。
  • 抢占式调度:优先级高的线程优先使用CPU,优先级相同则随机选择。Java使用抢占式调度。
  • 设置线程优先级可通过任务管理器打开详细信息,右键设置线程优先级。

    创建线程类

    Java中,java.lang.Thread类代表线程。所有线程类必须继承Thread或实现Runnable接口。

    使用Runnable接口

  • 定义实现类,重写run()方法。
  • 创建实现类实例。
  • 调用start()方法启动线程。
  • 示例:

    public class Demo04 implements Runnable {    @Override    public void run() {        for (int i = 0; i < 3; i++) {            System.out.println(Thread.currentThread().getName() + i);        }    }}public class test1 {    public static void main(String[] args) {        Demo04 obj = new Demo04();        Thread thread1 = new Thread(obj, "线程");        thread1.start();    }}

    匿名内部类方式

    public class Demo05 {    public static void main(String[] args) {        Runnable r = new Runnable() {            @Override            public void run() {                System.out.println(Thread.currentThread().getName());            }        };        new Thread(r).start();        for (int i = 0; i < 4; i++) {            System.out.println(Thread.currentThread().getName() + i);        }    }}

    线程安全问题

    线程安全指多线程同时运行,结果与单线程相同。解决方法是通过同步机制。

    线程同步

  • 同步代码块:使用synchronized关键字。
  • 同步方法:使用synchronized修饰方法。
  • 锁机制:使用Lock对象。
  • 示例:

    public class Demo07 implements Runnable {    private int num = 10;    Object lock = new Object();    @Override    public void run() {        while (true) {            synchronized (lock) {                if (num > 0) {                    try {                        Thread.sleep(100);                    } catch (InterruptedException e) {                        e.printStackTrace();                    } finally {                        lock.unlock();                    }                    System.out.println(Thread.currentThread().getName() + "数字为:" + num--);                }            }        }    }}class test2 {    public static void main(String[] args) {        Demo07 x = new Demo07();        Thread a = new Thread(x, "线程a");        Thread b = new Thread(x, "线程b");        a.start();        b.start();    }}

    Lock锁

    public class Demo09 implements Runnable {    private int num = 10;    Lock lock = new ReentrantLock();    @Override    public void run() {        while (true) {            lock.lock();            try {                if (num > 0) {                    try {                        Thread.sleep(100);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    lock.unlock();                    System.out.println(Thread.currentThread().getName() + "数字为:" + num--);                }            } finally {                lock.unlock();            }        }    }}class test5 {    public static void main(String[] args) {        Demo09 obj = new Demo09();        Thread thread = new Thread(obj, "线程x");        thread.start();    }}

    线程状态

    线程状态包括:NEW、Runnable、Blocked、Waiting、Timed Waiting、Terminated。

    Timed Waiting

    public class Demo10 extends Thread {    public void run() {        for (int i = 0; i < 100; i++) {            if (i % 10 == 0) {                System.out.println("——————" + i);            }            System.out.println(i);            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) {        new Demo10().start();    }}

    Waiting状态

    public class Demo11 {    public static Object obj = new Object();    public static void main(String[] args) {        Thread waitingThread = new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    synchronized (obj) {                        System.out.println(Thread.currentThread().getName() + "获取到锁对象,调用wait方法");                        obj.wait();                        System.out.println(Thread.currentThread().getName() + "从waiting状态醒来");                    }                }            }        }, "等待线程").start();        Thread awakeningThread = new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    System.out.println(Thread.currentThread().getName() + "——等待3秒钟");                    try {                        Thread.sleep(3000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    synchronized (obj) {                        System.out.println(Thread.currentThread().getName() + "获取到锁对象,调用notify方法");                        obj.notify();                    }                }            }        }, "唤醒线程").start();    }}

    线程池

    线程池用于高效管理多线程任务,避免频繁启动线程。

    创建线程池

    public class Demo12_ThreadPool {    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(6);        Runnable obj1 = new Runnable() {            @Override            public void run() {                System.out.println(Thread.currentThread().getName() + "执行");            }        };        Runnable obj2 = new Runnable() {            @Override            public void run() {                System.out.println(Thread.currentThread().getName() + "执行");            }        };        pool.submit(obj1);        pool.submit(obj2);        pool.shutdown();    }}

    线程池提供了灵活的任务处理方式,适合高并发环境。通过合理配置线程池大小,可以优化系统性能。

    转载地址:http://qzxkz.baihongyu.com/

    你可能感兴趣的文章
    Nginx + uWSGI + Flask + Vhost
    查看>>
    Nginx Location配置总结
    查看>>
    Nginx 反向代理解决跨域问题
    查看>>
    nginx 后端获取真实ip
    查看>>
    Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
    查看>>
    nginx 常用配置记录
    查看>>
    Nginx 我们必须知道的那些事
    查看>>
    nginx 配置~~~本身就是一个静态资源的服务器
    查看>>
    Nginx的是什么?干什么用的?
    查看>>
    Nio ByteBuffer组件读写指针切换原理与常用方法
    查看>>
    NI笔试——大数加法
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
    查看>>
    NSSet集合 无序的 不能重复的
    查看>>
    nullnullHuge Pages
    查看>>
    Numpy如何使用np.umprod重写range函数中i的python
    查看>>
    oauth2-shiro 添加 redis 实现版本
    查看>>
    OAuth2.0_JWT令牌-生成令牌和校验令牌_Spring Security OAuth2.0认证授权---springcloud工作笔记148
    查看>>
    OAuth2.0_JWT令牌介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记147
    查看>>