当前位置:首页 > 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关键字可以修饰方法或代码块,保证同一时间只有一个线程执行。

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方法请求中断,被中断线程需要检查中断状态并做出响应。

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,可以在多线程环境下安全使用。

java线程如何使用

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

分享给朋友:

相关文章

react如何使用redux

react如何使用redux

使用 Redux 在 React 中的应用 Redux 是一个状态管理库,通常与 React 结合使用以管理全局状态。以下是具体实现步骤: 安装依赖 确保项目中已安装 redux 和 react-r…

react thunk 如何使用

react thunk 如何使用

使用 React Thunk 的基本步骤 安装 Redux 和 Redux Thunk 作为依赖项: npm install redux redux-thunk 在 Redux store 配置中应…

react激光如何使用

react激光如何使用

安装React激光库 在项目中安装React激光库,通常通过npm或yarn完成。确保项目已初始化并具备React环境。 npm install react-laser-beam # 或 yar…

react如何使用dispatch

react如何使用dispatch

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

react如何使用插槽

react如何使用插槽

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

web项目如何使用react

web项目如何使用react

使用 React 构建 Web 项目的关键步骤 环境准备 安装 Node.js 和 npm(或 yarn),确保开发环境支持现代 JavaScript。通过以下命令创建 React 项目: np…