如何控制java线程
控制Java线程的方法
线程的创建与启动
在Java中,线程可以通过继承Thread类或实现Runnable接口来创建。实现Runnable接口更灵活,因为Java不支持多重继承。线程启动需要调用start()方法,而不是直接调用run()方法。
// 实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
// 启动线程
Thread thread = new Thread(new MyRunnable());
thread.start();
线程同步
多线程环境下,共享资源的访问可能导致数据不一致。可以使用synchronized关键字或Lock接口实现线程同步。
// 使用synchronized方法
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
// 使用ReentrantLock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程间通信
wait()、notify()和notifyAll()方法用于线程间通信。这些方法必须在同步块或同步方法中调用。
class SharedResource {
private boolean ready = false;
public synchronized void waitUntilReady() throws InterruptedException {
while (!ready) {
wait();
}
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}
线程池管理
使用线程池可以避免频繁创建和销毁线程的开销。ExecutorService提供了线程池的管理功能。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task running in thread pool");
});
executor.shutdown();
线程中断
通过调用interrupt()方法可以中断线程。线程需要检查中断状态并做出响应。
class InterruptibleTask implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Thread thread = new Thread(new InterruptibleTask());
thread.start();
thread.interrupt();
线程状态监控
Thread类提供了getState()方法用于获取线程状态。线程状态包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED。

Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(thread.getState()); // NEW
thread.start();
System.out.println(thread.getState()); // RUNNABLE






