博客
关于我
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/

    你可能感兴趣的文章
    Objective-C实现merge sort归并排序算法(附完整源码)
    查看>>
    Objective-C实现mergesort归并排序算法(附完整源码)
    查看>>
    Objective-C实现miller rabin米勒-拉宾素性检验算法(附完整源码)
    查看>>
    Objective-C实现Miller-Rabin素性测试程序(附完整源码)
    查看>>
    Objective-C实现Miller-Rabin素性测试程序(附完整源码)
    查看>>
    Objective-C实现MinhashLSH算法(附完整源码)
    查看>>
    Objective-C实现MinhashLSH算法(附完整源码)
    查看>>
    Objective-C实现MinHeap最小堆算法(附完整源码)
    查看>>
    Objective-C实现MSRCR算法(附完整源码)
    查看>>
    Objective-C实现multilayer perceptron classifier多层感知器分类器算法(附完整源码)
    查看>>
    Objective-C实现multiplesThreeAndFive三或五倍数的算法 (附完整源码)
    查看>>
    Objective-C实现n body simulationn体模拟算法(附完整源码)
    查看>>
    Objective-C实现naive string search字符串搜索算法(附完整源码)
    查看>>
    Objective-C实现natural sort自然排序算法(附完整源码)
    查看>>
    Objective-C实现nested brackets嵌套括号算法(附完整源码)
    查看>>
    Objective-C实现nevilles method多项式插值算法(附完整源码)
    查看>>
    Objective-C实现newtons second law of motion牛顿第二运动定律算法(附完整源码)
    查看>>
    Objective-C实现newton_raphson牛顿拉夫森算法(附完整源码)
    查看>>
    Objective-C实现NLP中文分词(附完整源码)
    查看>>
    Objective-C实现NLP中文分词(附完整源码)
    查看>>