java线程 如何实现
线程创建方式
Java中实现线程主要有两种方式:继承Thread类或实现Runnable接口。
继承Thread类
通过继承Thread类并重写run()方法定义线程逻辑:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread");
}
}
// 启动线程
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
通过实现Runnable接口并实现run()方法,再将实例传递给Thread对象:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable");
}
}
// 启动线程
Thread thread = new Thread(new MyRunnable());
thread.start();
线程池管理
推荐使用线程池(如ExecutorService)管理线程,避免频繁创建销毁线程的开销:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
线程同步
多线程共享资源时需使用同步机制:
synchronized关键字
修饰方法或代码块,确保同一时间只有一个线程访问资源:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
Lock接口
通过ReentrantLock实现更灵活的同步控制:
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程通信
使用wait()、notify()或Condition实现线程间协作:
class SharedResource {
private boolean flag = false;
public synchronized void waitForFlag() throws InterruptedException {
while (!flag) {
wait();
}
}
public synchronized void setFlag() {
flag = true;
notifyAll();
}
}
线程中断
通过interrupt()方法请求终止线程,线程需检查中断状态并响应:

Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
thread.start();
thread.interrupt();
注意事项
- 避免直接调用
run()方法,需通过start()启动线程。 - 优先选择
Runnable接口,避免单继承限制。 - 使用线程池时注意合理配置核心线程数和队列容量。
- 同步代码块应尽量缩小范围,减少性能影响。






