Java多线程常用的方法有哪些

发布时间:2022-11-16 09:17:51 作者:iii
来源:亿速云 阅读:135

Java多线程常用的方法有哪些

目录

  1. 引言
  2. 线程的创建与启动
  3. 线程的生命周期
  4. 线程的常用方法
  5. 线程同步
  6. 线程池
  7. 并发集合
  8. 线程间通信
  9. 线程安全
  10. 总结

引言

在Java编程中,多线程是一个非常重要的概念。多线程允许程序同时执行多个任务,从而提高程序的效率和响应速度。Java提供了丰富的多线程API,使得开发者可以轻松地创建和管理线程。本文将详细介绍Java多线程中常用的方法,帮助读者更好地理解和应用多线程编程。

线程的创建与启动

继承Thread类

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

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

实现Runnable接口

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }
}

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

实现Callable接口

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyCallable implements Callable<String> {
    public String call() {
        return "Thread is running";
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        FutureTask<String> task = new FutureTask<>(new MyCallable());
        Thread thread = new Thread(task);
        thread.start();
        System.out.println(task.get());
    }
}

线程的生命周期

新建状态

线程对象被创建后,处于新建状态。

就绪状态

调用start()方法后,线程进入就绪状态,等待CPU调度。

运行状态

线程获得CPU资源后,进入运行状态,执行run()方法。

阻塞状态

线程由于某些原因(如等待I/O操作、调用sleep()方法等)暂时停止执行,进入阻塞状态。

终止状态

线程执行完run()方法后,进入终止状态。

线程的常用方法

start()

启动线程,使其进入就绪状态。

thread.start();

run()

线程执行的主体方法。

public void run() {
    // 线程执行的代码
}

sleep()

使当前线程暂停执行指定的时间(毫秒)。

Thread.sleep(1000); // 暂停1秒

join()

等待该线程终止。

thread.join(); // 等待thread线程终止

yield()

暂停当前线程,让出CPU资源给其他线程。

Thread.yield();

interrupt()

中断线程。

thread.interrupt();

isInterrupted()

判断线程是否被中断。

if (thread.isInterrupted()) {
    // 线程被中断
}

setPriority()

设置线程的优先级。

thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级

getPriority()

获取线程的优先级。

int priority = thread.getPriority();

setDaemon()

设置线程为守护线程。

thread.setDaemon(true);

isDaemon()

判断线程是否为守护线程。

if (thread.isDaemon()) {
    // 线程是守护线程
}

currentThread()

获取当前线程的引用。

Thread currentThread = Thread.currentThread();

getName()

获取线程的名称。

String name = thread.getName();

setName()

设置线程的名称。

thread.setName("MyThread");

getId()

获取线程的ID。

long id = thread.getId();

getState()

获取线程的状态。

Thread.State state = thread.getState();

isAlive()

判断线程是否处于活动状态。

if (thread.isAlive()) {
    // 线程处于活动状态
}

线程同步

synchronized关键字

用于修饰方法或代码块,确保同一时间只有一个线程执行该代码。

synchronized void method() {
    // 同步代码
}

wait()

使当前线程等待,直到其他线程调用notify()notifyAll()方法。

synchronized (obj) {
    obj.wait();
}

notify()

唤醒在此对象监视器上等待的单个线程。

synchronized (obj) {
    obj.notify();
}

notifyAll()

唤醒在此对象监视器上等待的所有线程。

synchronized (obj) {
    obj.notifyAll();
}

ReentrantLock

可重入锁,提供比synchronized更灵活的锁机制。

ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // 同步代码
} finally {
    lock.unlock();
}

Condition

ReentrantLock配合使用,提供更细粒度的线程通信。

Condition condition = lock.newCondition();
condition.await(); // 等待
condition.signal(); // 唤醒

线程池

Executor框架

用于管理线程池的框架。

Executor executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {
    public void run() {
        // 任务代码
    }
});

ThreadPoolExecutor

自定义线程池。

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    5, // 核心线程数
    10, // 最大线程数
    60, // 空闲线程存活时间
    TimeUnit.SECONDS, // 时间单位
    new LinkedBlockingQueue<>() // 任务队列
);
executor.execute(new Runnable() {
    public void run() {
        // 任务代码
    }
});

Executors工具类

提供创建线程池的工厂方法。

ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
    public void run() {
        // 任务代码
    }
});

ScheduledExecutorService

支持定时任务的线程池。

ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(new Runnable() {
    public void run() {
        // 任务代码
    }
}, 10, TimeUnit.SECONDS); // 10秒后执行

并发集合

ConcurrentHashMap

线程安全的HashMap。

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key", "value");

CopyOnWriteArrayList

线程安全的ArrayList。

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("element");

BlockingQueue

线程安全的队列。

BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("element");
String element = queue.take();

线程间通信

管道通信

使用PipedInputStreamPipedOutputStream进行线程间通信。

PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);

new Thread(() -> {
    try {
        out.write("Hello".getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

new Thread(() -> {
    try {
        byte[] buffer = new byte[1024];
        int len = in.read(buffer);
        System.out.println(new String(buffer, 0, len));
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

信号量

使用Semaphore控制资源的访问。

Semaphore semaphore = new Semaphore(2);

new Thread(() -> {
    try {
        semaphore.acquire();
        // 访问资源
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        semaphore.release();
    }
}).start();

CountDownLatch

等待多个线程完成。

CountDownLatch latch = new CountDownLatch(3);

new Thread(() -> {
    // 任务代码
    latch.countDown();
}).start();

latch.await(); // 等待所有线程完成

CyclicBarrier

等待多个线程到达某个屏障点。

CyclicBarrier barrier = new CyclicBarrier(3);

new Thread(() -> {
    try {
        // 任务代码
        barrier.await();
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

Exchanger

两个线程交换数据。

Exchanger<String> exchanger = new Exchanger<>();

new Thread(() -> {
    try {
        String data = exchanger.exchange("Hello");
        System.out.println(data);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

new Thread(() -> {
    try {
        String data = exchanger.exchange("World");
        System.out.println(data);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

线程安全

原子类

使用AtomicInteger等原子类保证线程安全。

AtomicInteger atomicInteger = new AtomicInteger(0);
atomicInteger.incrementAndGet();

volatile关键字

保证变量的可见性。

volatile boolean flag = true;

ThreadLocal

为每个线程提供独立的变量副本。

ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("Hello");
String value = threadLocal.get();

总结

Java多线程编程是一个复杂而强大的领域,掌握常用的多线程方法和技巧对于编写高效、稳定的并发程序至关重要。本文详细介绍了Java多线程中常用的方法,包括线程的创建与启动、生命周期、常用方法、线程同步、线程池、并发集合、线程间通信以及线程安全等内容。希望本文能帮助读者更好地理解和应用Java多线程编程。

推荐阅读:
  1. 常用的js方法有哪些
  2. Map的常用方法有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Vue中vee-validate插件怎么安装使用

下一篇:Vue怎么实现Excel上传功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》