java 如何使用线程
线程的基本使用
在Java中,线程可以通过继承Thread类或实现Runnable接口来创建。继承Thread类需要重写run方法,而实现Runnable接口需要实现run方法。
// 继承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方法。start方法会创建一个新的线程并执行run方法中的代码。
// 继承Thread类的方式
MyThread thread1 = new MyThread();
thread1.start();
// 实现Runnable接口的方式
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
线程同步
多线程环境下,共享资源的访问可能会导致数据不一致。使用synchronized关键字可以确保同一时间只有一个线程访问共享资源。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
线程池的使用
Java提供了ExecutorService来管理线程池,避免频繁创建和销毁线程的开销。Executors类提供了多种线程池的创建方法。
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
线程间通信
wait和notify方法用于线程间的通信。wait使当前线程等待,notify唤醒等待中的线程。
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) {
wait();
}
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}
线程中断
通过调用interrupt方法可以中断线程。线程需要检查中断状态并做出响应。
class InterruptibleThread extends Thread {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running");
}
System.out.println("Thread interrupted");
}
}
InterruptibleThread thread = new InterruptibleThread();
thread.start();
thread.interrupt();
线程局部变量
ThreadLocal类可以为每个线程提供独立的变量副本,避免共享变量的线程安全问题。
ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "Initial Value");
System.out.println(threadLocal.get()); // Output: Initial Value
threadLocal.set("New Value");
System.out.println(threadLocal.get()); // Output: New Value
线程状态
线程的生命周期包括新建(NEW)、就绪(RUNNABLE)、运行(RUNNING)、阻塞(BLOCKED)、等待(WAITING)、超时等待(TIMED_WAITING)和终止(TERMINATED)状态。
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(thread.getState()); // Output: NEW
thread.start();
System.out.println(thread.getState()); // Output: RUNNABLE
线程优先级
线程优先级范围从1(最低)到10(最高),默认优先级为5。优先级高的线程更有可能被调度执行。
Thread thread = new Thread(() -> System.out.println("Running"));
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
守护线程
守护线程是为其他线程提供服务的线程,当所有非守护线程结束时,守护线程会自动终止。通过setDaemon方法设置。

Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("Daemon thread running");
}
});
daemonThread.setDaemon(true);
daemonThread.start();






