java线程如何使用
创建线程的两种主要方式
在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,可以在多线程环境下安全使用。
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
System.out.println(map.get("key")); // 输出1






