【Java菜鸟学习进阶路线】Java进阶知识篇之多线程编程

Java多线程是指在一个进程内有多个执行路径或控制单元,每个单元被称为一个线程。每个线程都有自己的栈、程序计数器和局部变量等独立的运行资源。这种设计使得多个线程可以同时运行,每个线程并行处理不同的任务,从而提高了整体的执行效率。

线程的周期

  1. 新建(New):线程对象被创建后,就进入了新建状态。此时,线程对象已经分配了内存空间,但还没有调用start()方法启动线程。

  2. 就绪(Runnable):当调用线程对象的start()方法后,线程进入就绪状态。此时,线程对象已经具备了运行条件,等待系统为其分配CPU资源。在就绪状态下的线程有可能立即获得CPU资源并开始执行,也可能因为其他线程占用了CPU资源而暂时无法执行。

  3. 运行(Running):当线程获得CPU资源并开始执行时,线程进入运行状态。此时,线程正在执行其run()方法中的代码。

  4. 阻塞(Blocked):线程在运行过程中可能会遇到某些条件不满足的情况,导致线程进入阻塞状态。例如,线程在等待I/O操作完成、等待获取锁等情况下会进入阻塞状态。在阻塞状态下,线程暂时无法继续执行。

  5. 等待(Waiting):线程在某些情况下需要主动放弃对共享资源的占用权,进入等待状态。例如,线程在调用Object类的wait()方法或Thread类的join()方法时会进入等待状态。在等待状态下,线程暂时无法继续执行,直到其他线程唤醒它或者超时。

  6. 超时等待(Timed Waiting):与等待状态类似,但等待时间有限。当等待超过指定的时间后,线程会自动返回到等待队列中重新竞争资源。

  7. 终止(Terminated):当线程执行完run()方法中的代码或者因为异常而终止时,线程进入终止状态。此时,线程已经结束运行,不再占用系统资源。

Java多线程的优点

  1. 提高系统吞吐率:多线程编程可以使一个进程有多个并发的操作,从而提高系统的处理能力。
  2. 更好地利用系统资源:采用多线程技术的应用程序可以更充分地利用CPU的空闲时间片,以更少的时间响应用户请求,从而提高进程的整体运行效率。
  3. 增强应用程序的灵活性:由于同一进程的所有线程共享同一内存,不需要特殊的数据传送机制,也不需要建立共享存储区或共享文件,从而使得不同任务之间的协调操作与运行、数据的交互、资源的分配等问题更加易于解决。
  4. 简化程序设计:在某些情况下,多线程程序设计可能比单线程程序设计更简单。

Java多线程的使用

  1. 创建线程:Java中可以通过两种方式创建线程,一种是通过实现Runnable接口来创建线程,另一种是通过继承Thread类来创建线程。

  2. 启动线程:创建线程后,需要调用start()方法来启动线程,该方法会调用线程的run()方法。

  3. 控制线程:Java提供了一些方法来控制线程的执行,例如sleep()方法可以让线程暂停执行一段时间,join()方法可以让当前线程等待另一个线程执行完毕后再继续执行。

  4. 同步线程:在多线程环境下,多个线程可能会同时访问共享资源,这可能会导致数据不一致的问题。为了避免这种情况,可以使用synchronized关键字来同步线程,确保同一时间只有一个线程能够访问共享资源。

  5. 结束线程:当线程完成任务后,需要调用stop()方法来结束线程。但需要注意的是,由于stop()方法是过期的API,因此不推荐使用。更好的做法是设置一个标志位,让线程在某个条件满足时自行退出循环并结束。

如何创建线程

  1. 实现Runnable接口:创建一个类,实现Runnable接口,并重写run()方法。然后在主程序中创建该类的实例,并将其作为参数传递给Thread类的构造函数来创建线程。
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("This is a thread.");
    }
}

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

  1. 继承Thread类:创建一个类,继承Thread类,并重写run()方法。然后在主程序中创建该类的实例,调用start()方法来启动线程。
class MyThread extends Thread {
    public void run() {
        System.out.println("This is a thread.");
    }
}

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

两种方式的对比
  1. 实现方式不同:继承Thread类需要重写run()方法,而实现Runnable接口需要重写run()方法。

  2. 适用场景不同:继承Thread类适合于单继承的情况,因为Java不支持多重继承;而实现Runnable接口适合于多继承的情况,因为Java支持多重继承。

  3. 资源消耗不同:由于Java不支持多重继承,因此继承Thread类的子类不能再继承其他类;而实现Runnable接口的类可以继续继承其他类。此外,由于Java不支持多重继承,因此使用继承Thread类的方式创建线程时,每个线程都会占用一定的系统资源(比如内存),而使用实现Runnable接口的方式创建线程时,每个线程只会占用很少的系统资源。

  4. 代码可读性不同:由于实现Runnable接口的方式更加灵活,可以方便地创建多个线程,因此这种方式的代码可读性更好。

线程安全

什么是线程安全

线程安全是指在多线程环境下,多个线程同时访问共享资源时,程序的行为仍然能够按照预期的方式进行,不会出现数据竞争、死锁等异常情况。在多线程编程中,由于多个线程可能会同时访问和修改同一块内存空间,因此需要采取一些措施来保证线程安全。这些措施包括使用同步机制(如synchronized关键字、Lock接口及其实现类等)来保证各个线程都能够正常且准确地执行,或者使用原子操作类(如AtomicInteger、AtomicLong等)来执行无锁的多个操作。此外,也可以通过使用并发容器(如ConcurrentHashMap、CopyOnWriteArrayList等)或volatile关键字来确保线程安全。简而言之,线程安全的最终目标就是正确的结果等于安全。

Java中如何保证线程安全

  1. 使用synchronized关键字:通过在方法或代码块上添加synchronized关键字,可以确保同一时间只有一个线程能够访问该方法或代码块。
public class SynchronizedExample {
    private int count = 0;

    // 使用synchronized关键字修饰方法
    public synchronized void increment() {
        count++;
        System.out.println("当前计数值:" + count);
    }

    public static void main(String[] args) {
        SynchronizedExample example = new SynchronizedExample();

        // 创建两个线程,分别调用increment方法
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });

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

        // 启动线程
        thread1.start();
        thread2.start();

        // 等待线程执行完毕
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
		
		// 输出2000
        System.out.println("最终计数值:" + example.count);
    }
}

  1. 使用Lock接口及其实现类(如ReentrantLock):Lock接口提供了与synchronized关键字类似的功能,但更加灵活。它允许多个线程同时访问共享资源,但需要手动控制锁的获取和释放。
  • lock():获取锁,如果锁已经被其他线程持有,则当前线程会阻塞等待。
  • unlock():释放锁,只有持有锁的线程才能调用此方法。
  • tryLock():尝试获取锁,如果锁已经被其他线程持有,则立即返回false,否则获取锁并返回true。
  • lockInterruptibly():与tryLock()类似,但是当锁被其他线程持有时,当前线程会抛出InterruptedException异常。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private final Lock lock = new ReentrantLock();

    public void doSomething() {
        lock.lock(); // 获取锁
        try {
            // 临界区代码
            System.out.println("执行临界区代码");
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    public static void main(String[] args) {
        LockExample example = new LockExample();
        example.doSomething();
    }
}

  1. 使用原子操作类(如AtomicInteger、AtomicLong等):原子操作类提供了一种无锁的方式来执行多个操作,从而避免了竞争条件的发生。
  • AtomicInteger:原子整数类,提供原子操作的整数值
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        int oldValue, newValue;

        do {
            oldValue = atomicInteger.get();
            newValue = oldValue + 1;
        } while (!atomicInteger.compareAndSet(oldValue, newValue));

        System.out.println("AtomicInteger value: " + atomicInteger.get());
    }
}

  • AtomicLong:原子长整数类,提供原子操作的长整数值。
import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongDemo {
    public static void main(String[] args) {
        AtomicLong atomicLong = new AtomicLong(0);
        long oldValue, newValue;

        do {
            oldValue = atomicLong.get();
            newValue = oldValue + 1;
        } while (!atomicLong.compareAndSet(oldValue, newValue));

        System.out.println("AtomicLong value: " + atomicLong.get());
    }
}

  • AtomicBoolean:原子布尔类,提供原子操作的布尔值。
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanDemo {
    public static void main(String[] args) {
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        boolean oldValue, newValue;

        do {
            oldValue = atomicBoolean.get();
            newValue = !oldValue;
        } while (!atomicBoolean.compareAndSet(oldValue, newValue));

        System.out.println("AtomicBoolean value: " + atomicBoolean.get());
    }
}

  1. 使用并发容器(如ConcurrentHashMap、CopyOnWriteArrayList等):并发容器是一种特殊的数据结构,可以在多线程环境下提供高效的并发访问。它们内部使用了各种同步机制来保证线程安全。

  2. 使用volatile关键字:volatile关键字可以确保变量的可见性,即当一个线程修改了变量的值后,其他线程能够立即看到修改后的值。但它不能保证复合操作的原子性,因此不能替代synchronized关键字。

public class VolatileExample {
    private volatile boolean flag = false;

    public void setFlag(boolean value) {
        this.flag = value;
    }

    public boolean getFlag() {
        return flag;
    }

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

        // 创建两个线程,分别设置和获取flag的值
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                example.setFlag(true);
                System.out.println("Thread 1 set flag to true");
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("Thread 2 get flag: " + example.getFlag());
            }
        });

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

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

线程的通信

  1. 共享内存:线程之间共享数据,通过读写这些数据来实现通信。这种方式需要特别注意同步问题,避免出现竞态条件。
public class SharedMemoryExample {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class IncrementThread extends Thread {
    private SharedMemoryExample sharedMemory;

    public IncrementThread(SharedMemoryExample sharedMemory) {
        this.sharedMemory = sharedMemory;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            sharedMemory.increment();
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        SharedMemoryExample sharedMemory = new SharedMemoryExample();
        IncrementThread thread1 = new IncrementThread(sharedMemory);
        IncrementThread thread2 = new IncrementThread(sharedMemory);

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

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

        System.out.println("最终计数值:" + sharedMemory.getCount());
    }
}

  1. 消息传递:线程之间通过发送和接收消息来通信。这种方式可以避免同步问题,但需要考虑消息的可靠性和顺序性等问题。
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MessagePassingExample {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>();

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

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

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

class Producer extends Thread {
    private BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 1000; i++) {
                String message = "Message " + i;
                queue.put(message);
                System.out.println("生产者发送消息:" + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer extends Thread {
    private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = queue.take();
                System.out.println("消费者接收消息:" + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

总结

Java多线程在实际编码应用中比较广泛,可以提高接口响应速度和提升处理数据的速度。当然,在使用Java多线程时,需要注意一些事项,否则会造成不可预估的后果。

  1. 要避免共享资源的竞争条件,这可能导致数据不一致或程序崩溃。
  2. 需要避免死锁,即多个线程互相等待对方释放资源而导致的程序停滞
  3. 要注意线程安全,确保数据在并发访问时的正确性。
  4. 合理的线程数量也非常重要,避免过多线程导致系统资源过度消耗

下一章将继续介绍线程池的使用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值