深入理解Java中的多线程编程模型

大家好,我是微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!

多线程编程概述

在Java中,多线程编程是一种利用多个线程同时执行任务来提高程序性能的编程模型。Java提供了丰富的API支持,使得开发者可以轻松地创建和管理多线程应用。

1. 创建线程的方式

1.1 继承Thread类

package cn.juwatech.example;

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("Thread running: " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

1.2 实现Runnable接口

package cn.juwatech.example;

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("Runnable running: " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

2. 线程同步与互斥

2.1 synchronized关键字

package cn.juwatech.example;

public class SynchronizedCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedCounter counter = new SynchronizedCounter();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Count: " + counter.getCount());
    }
}

2.2 使用Lock接口

package cn.juwatech.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCounter {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        LockCounter counter = new LockCounter();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Count: " + counter.getCount());
    }
}

3. 线程间通信

3.1 使用wait()和notify()

package cn.juwatech.example;

public class WaitNotifyExample {

    public static void main(String[] args) throws InterruptedException {
        Message message = new Message();

        Thread producer = new Thread(new Producer(message));
        Thread consumer = new Thread(new Consumer(message));

        producer.start();
        consumer.start();

        producer.join();
        consumer.join();
    }
}

class Message {
    private String content;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = true;
        notifyAll();
        return content;
    }

    public synchronized void write(String content) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = false;
        this.content = content;
        notifyAll();
    }
}

class Producer implements Runnable {
    private Message message;

    public Producer(Message message) {
        this.message = message;
    }

    @Override
    public void run() {
        String[] messages = {"Message 1", "Message 2", "Message 3"};
        for (String msg : messages) {
            message.write(msg);
            System.out.println("Produced: " + msg);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    private Message message;

    public Consumer(Message message) {
        this.message = message;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            String msg = message.read();
            System.out.println("Consumed: " + msg);
        }
    }
}

4. 线程池的使用

4.1 使用Executors工具类

package cn.juwatech.example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Runnable task1 = () -> {
            System.out.println("Task 1 executed by thread: " + Thread.currentThread().getName());
        };

        Runnable task2 = () -> {
            System.out.println("Task 2 executed by thread: " + Thread.currentThread().getName());
        };

        executor.submit(task1);
        executor.submit(task2);

        executor.shutdown();
    }
}

结论

本文深入探讨了Java中的多线程编程模型,从线程的创建方式、线程同步与互斥、线程间通信到线程池的使用等方面展开了讲解。通过学习本文,读者可以更加深入地理解和应用Java多线程编程,提高程序的并发处理能力。

微赚淘客系统3.0小编出品,必属精品,转载请注明出处!