实例代码讲解JAVA多线程

下面我将详细讲解“实例代码讲解JAVA多线程”的完整攻略,包含如下内容:

一、多线程基础知识

1. 线程的概念及创建

线程是指在单个程序中同时运行的多个执行单元,每个线程都有独立的执行路径。Java中通过继承Thread类或实现Runnable接口的方式创建线程,具体代码实例如下:

public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
        System.out.println("Main thread running...");
    }
}

运行以上代码,控制台将输出:

Main thread running...
MyThread running...

这证明主线程和子线程是交替运行的。

2. 线程的状态

Java中线程有五种状态:新建(NEW)、就绪(RUNNABLE)、运行(RUNNING)、阻塞(BLOCKED)和死亡(DEAD)。线程的状态由操作系统内核维护和切换。

3. 线程的同步与互斥

多个线程执行时访问共享资源会发生冲突,需要进行同步或互斥处理,防止出现数据不一致等问题。Java中通过synchronized关键字进行同步,通过Lock接口进行互斥。

二、Java多线程实例

1. 生产者消费者模型

生产者消费者模型是多个线程协作的典型场景,生产者生产数据并交给缓冲区,消费者从缓冲区取出数据进行消费。以下代码实现生产者消费者模型:

public class Producer extends Thread {
    private Buffer buffer;
    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }
    public void run() {
        for (int i=1; i<=10; i++) {
            buffer.put(i);
            System.out.println("Producer produce: " + i);
            try {
                Thread.sleep((int)(Math.random() * 200));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Producer finished producing.");
    }
}

public class Consumer extends Thread {
    private Buffer buffer;
    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }
    public void run() {
        for (int i=1; i<=10; i++) {
            int num = buffer.get();
            System.out.println("Consumer consume: " + num);
            try {
                Thread.sleep((int)(Math.random() * 200));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Consumer finished consuming.");
    }
}

public class Buffer {
    private int[] buffer = new int[10];
    private int head = 0;
    private int tail = 0;
    private int count = 0;

    public synchronized void put(int num) {
        while (count == buffer.length) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buffer[tail] = num;
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();
    }

    public synchronized int get() {
        while (count == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int num = buffer[head];
        head = (head + 1) % buffer.length;
        count--;
        notifyAll();
        return num;
    }
}

public class Main {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Producer producer = new Producer(buffer);
        Consumer consumer = new Consumer(buffer);
        producer.start();
        consumer.start();
    }
}

这段代码实现了一个简单的生产者消费者模型,通过使用synchronized关键字,实现了对缓冲区的同步访问和互斥访问,生产者可以把数据放入缓冲区,消费者可以从缓冲区取出数据进行消费,两个线程之间互相协作完成工作。

2. 线程池

多线程编程时,频繁地创建和销毁线程会带来大量的资源消耗,此时应该采用线程池的机制,将线程的创建和生命周期管理由线程池来负责。以下代码实现一个简单的线程池:

public class ThreadPool {
    private List<WorkerThread> threads = new ArrayList<WorkerThread>();
    private LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
    private boolean stopped = false;

    public ThreadPool(int numThreads) {
        for (int i=0; i<numThreads; i++) {
            WorkerThread thread = new WorkerThread();
            threads.add(thread);
            thread.start();
        }
    }
    public void execute(Runnable task) {
        synchronized (taskQueue) {
            taskQueue.add(task);
            taskQueue.notifyAll();
        }
    }
    public void shutdown() {
        stopped = true;
        synchronized (taskQueue) {
            taskQueue.notifyAll();
        }
        for (WorkerThread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {}
        }
    }
    private class WorkerThread extends Thread {
        public void run() {
            while (!stopped) {
                Runnable task = null;
                synchronized (taskQueue) {
                    if (taskQueue.isEmpty()) {
                        try {
                            taskQueue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    task = taskQueue.poll();
                }
                if (task != null) {
                    task.run();
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool(2);
        for (int i=1; i<=10; i++) {
            final int num = i;
            pool.execute(new Runnable() {
                public void run() {
                    System.out.println("Executing task " + num + " on thread " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        pool.shutdown();
    }
}

这段代码实现了一个具备固定线程数的线程池,可以提交多个任务到线程池并按顺序执行,线程池内的线程在任务处理完毕后会一直存在,等待下一个任务的到来。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:实例代码讲解JAVA多线程 - Python技术站

(0)
上一篇 2023年5月17日
下一篇 2023年5月17日

相关文章

  • Java基础之并发相关知识总结

    Java基础之并发相关知识总结 什么是并发? 并发是指多个线程在特定的时间段内运行,并且在同一个进程内共享资源。本质上,线程是 CPU 执行计算任务的最小单位,CPU 在多个线程之间切换运行,从而实现并发执行多个任务,提高系统的效率和吞吐量。 什么是线程? 线程是进程内部并发执行的一条路径,也是执行的最小单位。在 Java 中,一个程序至少有一个主线程,主线…

    多线程 2023年5月17日
    00
  • 浅谈Java高并发解决方案以及高负载优化方法

    浅谈Java高并发解决方案以及高负载优化方法 前言 Java是一门广泛应用于大型企业和Web应用领域的高级语言,由于其良好的跨平台性、良好的编程风格和高度优化的JVM,Java在高并发、高负载的场景下表现出色。 在本文中,我们将讲解Java高并发的解决方案以及高负载优化方法。 Java高并发解决方案 Java高并发是指Java应用程序在多个线程或进程同时运行…

    多线程 2023年5月16日
    00
  • python基础之并发编程(一)

    以下是“python基础之并发编程(一)”的完整攻略: 什么是并发编程 并发指的是程序的多个部分可以同时执行的能力。在计算机领域中,指的是通过多个线程或进程实现并行计算和任务处理。 并发编程是指在同一时间段内处理多个计算任务的编程方式,它涉及到多个线程或进程之间的协调和通信。在Python中,使用多线程和多进程都能实现并发编程。 Python中的多线程并发编…

    多线程 2023年5月17日
    00
  • C#线程队列用法实例分析

    C#线程队列用法实例分析 1. 什么是线程队列 线程队列指的是一种数据结构,它遵循“先进先出(FIFO)”的原则,即第一个入队的元素也会是第一个被出队的元素。在C#中,我们可以使用Queue<T>类来实现线程队列。 2. 线程队列的主要用途 线程队列常用于多线程编程中,以便按照一定顺序访问共享资源,避免数据竞争等多线程并发问题。 3. C#中线程…

    多线程 2023年5月16日
    00
  • Java并发编程示例(六):等待线程执行终止

    这里是关于“Java并发编程示例(六):等待线程执行终止”的完整攻略。 标题 Java并发编程示例(六):等待线程执行终止 简介 在Java并发编程中,常常需要等待一个线程或多个线程的执行终止,才能接着执行下一步的操作。这篇文章将介绍如何等待线程执行终止的几种方法,以及使用这些方法的示例。 阻塞等待线程执行终止的方法 使用Thread.join()方法 在主…

    多线程 2023年5月16日
    00
  • MySQL系列之十 MySQL事务隔离实现并发控制

    MySQL事务隔离实现并发控制是MySQL数据库中非常重要的一个功能,它能够实现对并发事务的隔离,避免出现并发访问数据库时的数据一致性问题。本文将为读者介绍MySQL事务隔离的基本概念、实现方式及其使用方法。 MySQL事务隔离的基本概念 MySQL事务隔离是指通过数据库隔离等级(Isolation Level)来实现多个并发事务间互不影响的机制。在MySQ…

    多线程 2023年5月16日
    00
  • Java 多线程的同步代码块详解

    Java 多线程的同步代码块详解 在Java中,多线程操作的时候,经常会出现多个线程共享同一个资源的情况。当多个线程同时访问共享资源时,会导致数据不一致的问题,这就需要用到同步代码块来解决。 什么是同步代码块? 同步代码块是Java中实现线程安全的一种机制,用来解决多个线程同时访问共享资源的并发问题。同步代码块是指用 synchronized 关键字修饰的一…

    多线程 2023年5月16日
    00
  • java并发编程专题(十一)—-(JUC原子类)数组类型详解

    Java并发编程专题(十一)—-(JUC原子类)数组类型详解 1. 前言 Java并发编程主要使用锁、volatile和原子操作三种方式来保证线程安全。而在这三种方式中,原子操作是性能最优秀、最方便的一种。而在原子操作中,JUC原子类是最常用的一种。 本篇文章将主要讨论JUC原子类中的数组类型,即AtomicIntegerArray、AtomicLong…

    多线程 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部