Java快速入门系列-5(Java进阶特性)-LMLPHP

5.1 多线程与并发编程

5.1.1 多线程基础

在Java中,多线程是通过Thread类或实现Runnable接口来创建和管理线程的。多线程使得程序能够同时执行多个任务,提高程序运行效率。

// 通过继承Thread类创建线程
public class MyThread extends Thread {
   
    @Override
    public void run() {
   
        System.out.println("Running in " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
   
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}

// 通过实现Runnable接口创建线程
public class RunnableExample implements Runnable {
   
    @Override
    public void run() {
   
        System.out.println("Running in " + Thread.currentThread().getName());
    }

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

5.1.2 线程同步与锁

在多线程环境下,可能会出现数据不一致的问题,这时就需要引入线程同步机制,如synchronized关键字和Lock接口。下面是一个简单的synchronized示例:

public class Counter {
   
    private int count = 0;

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

    public synchronized void decrement() {
   
        count--;
    }

    public synchronized int value() {
   
        return count;
    }
}

Java 5引入了java.util.concurrent.locks包,提供更灵活的锁机制,如ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class CounterWithLock {
   
    private final ReentrantLock lock = new ReentrantLock();
    private 
04-06 05:45