当前位置:首页 > Java

java线程如何使用

2026-02-04 21:15:42Java

创建线程的两种主要方式

在Java中,线程可以通过继承Thread类或实现Runnable接口来创建。继承Thread类需要重写run方法,实现Runnable接口则需要实现run方法。Runnable方式更灵活,推荐使用。

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

// 实现Runnable接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable running");
    }
}

启动线程

创建线程实例后,调用start方法启动线程。注意直接调用run方法不会创建新线程,而是在当前线程中执行。

// 继承方式启动
MyThread thread1 = new MyThread();
thread1.start();

// 实现Runnable方式启动
Thread thread2 = new Thread(new MyRunnable());
thread2.start();

线程状态管理

线程有新建、可运行、阻塞、等待、计时等待和终止等状态。可以使用isAlive方法检查线程是否存活,join方法等待线程结束。

Thread thread = new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
thread.start();

// 等待线程结束
thread.join();
System.out.println("Thread finished");

线程同步

当多个线程访问共享资源时,需要使用同步机制。synchronized关键字可以修饰方法或代码块,保证同一时间只有一个线程执行。

java线程如何使用

class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

线程池的使用

使用线程池可以避免频繁创建销毁线程的开销。Java提供了Executor框架来管理线程池。

ExecutorService executor = Executors.newFixedThreadPool(4);

for (int i = 0; i < 10; i++) {
    executor.execute(() -> {
        System.out.println("Task executed by " + Thread.currentThread().getName());
    });
}

executor.shutdown();

线程间通信

wait、notify和notifyAll方法可以实现线程间通信。这些方法必须在同步块或同步方法中调用。

class SharedResource {
    private boolean ready = false;

    public synchronized void waitForReady() throws InterruptedException {
        while (!ready) {
            wait();
        }
    }

    public synchronized void setReady() {
        ready = true;
        notifyAll();
    }
}

线程中断处理

线程可以通过interrupt方法请求中断,被中断线程需要检查中断状态并做出响应。

java线程如何使用

Thread thread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
});
thread.start();

// 请求中断
thread.interrupt();

线程局部变量

ThreadLocal类可以为每个线程创建变量的副本,避免共享变量带来的同步问题。

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

Thread thread1 = new Thread(() -> {
    threadLocal.set(1);
    System.out.println(threadLocal.get());  // 输出1
});

Thread thread2 = new Thread(() -> {
    System.out.println(threadLocal.get());  // 输出0
});

原子操作

java.util.concurrent.atomic包提供了原子变量类,如AtomicInteger,可以保证操作的原子性。

AtomicInteger atomicInt = new AtomicInteger(0);

atomicInt.incrementAndGet();
System.out.println(atomicInt.get());  // 输出1

并发集合

Java提供了线程安全的集合类,如ConcurrentHashMap,可以在多线程环境下安全使用。

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
System.out.println(map.get("key"));  // 输出1

分享给朋友:

相关文章

react如何使用swiper

react如何使用swiper

安装 Swiper 依赖 在 React 项目中使用 Swiper 前,需要安装 Swiper 的核心库和 React 组件库。通过 npm 或 yarn 安装以下依赖: npm install s…

react refs 如何使用

react refs 如何使用

React Refs 的基本概念 Refs 是 React 提供的一种访问 DOM 节点或 React 组件实例的方式。通常在 React 的数据流中,父子组件通过 props 进行通信,但在某些情况…

react filter如何使用

react filter如何使用

react filter 的基本用法 在 React 中,filter 通常用于筛选数组数据,常见于列表渲染或数据处理场景。filter 是 JavaScript 数组的原生方法,但在 React 中…

react如何使用jquery

react如何使用jquery

在 React 中使用 jQuery React 和 jQuery 的设计理念不同,React 基于虚拟 DOM 和数据驱动,而 jQuery 直接操作真实 DOM。若需在 React 中整合 jQu…

react如何使用dispatch

react如何使用dispatch

使用 useDispatch 钩子 在函数组件中,通过 react-redux 提供的 useDispatch 钩子获取 dispatch 函数。引入 useDispatch 后直接调用即可:…

react如何使用插槽

react如何使用插槽

使用props.children实现基础插槽 React中插槽的核心是通过props.children传递子组件。父组件在标签内部放置的内容会自动成为children属性: // 父组件 <C…