在java如何控制线程
控制线程的基本方法
Java中控制线程主要通过Thread类和Runnable接口实现。创建线程的方式有两种:继承Thread类或实现Runnable接口。以下是具体实现方式:
继承Thread类:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread t1 = new MyThread();
t1.start();
实现Runnable接口:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
Thread t2 = new Thread(new MyRunnable());
t2.start();
线程状态管理
Java线程有以下状态:NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED。通过Thread类的方法可以控制线程状态:
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000); // TIMED_WAITING状态
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start(); // 进入RUNNABLE状态
thread.join(); // 等待线程终止
线程同步机制
使用synchronized关键字或Lock接口实现线程同步:
synchronized方法:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
ReentrantLock:
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程间通信
使用wait()、notify()和notifyAll()方法实现线程间通信:
class SharedResource {
private boolean available = false;
public synchronized void produce() {
while(available) {
wait();
}
available = true;
notifyAll();
}
public synchronized void consume() {
while(!available) {
wait();
}
available = false;
notifyAll();
}
}
线程池管理
使用ExecutorService框架管理线程池:
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
线程中断处理
通过interrupt()方法中断线程,线程需要检查中断状态:
Thread thread = new Thread(() -> {
while(!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
thread.start();
thread.interrupt();
线程局部变量
使用ThreadLocal为每个线程维护独立的变量副本:

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
threadLocal.set(1);
int value = threadLocal.get();






