java 如何实现线程
线程的实现方式
在Java中,线程可以通过继承Thread类或实现Runnable接口来实现。以下是两种主要方法的详细说明。
继承Thread类
通过继承Thread类并重写其run()方法,可以创建自定义线程。以下是示例代码:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口
实现Runnable接口是更推荐的方式,因为Java不支持多重继承。以下是示例代码:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
线程的启动
无论使用哪种方式,线程的启动都需要调用start()方法。start()方法会调用run()方法并在新线程中执行。
使用Lambda表达式简化
从Java 8开始,可以使用Lambda表达式进一步简化代码:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.start();
}
}
线程池的使用
对于需要管理多个线程的场景,推荐使用线程池。以下是使用ExecutorService的示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(() -> {
System.out.println("Thread is running");
});
executor.shutdown();
}
}
线程同步
在多线程环境下,共享资源的访问需要同步。可以使用synchronized关键字或Lock接口:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.getCount());
}
}
线程的生命周期
线程的生命周期包括新建(New)、就绪(Runnable)、运行(Running)、阻塞(Blocked)和终止(Terminated)状态。Thread类提供了isAlive()、join()等方法用于管理线程状态。
线程优先级
线程优先级可以通过setPriority(int priority)方法设置,优先级范围从Thread.MIN_PRIORITY(1)到Thread.MAX_PRIORITY(10)。
Thread thread = new Thread(() -> {
System.out.println("Thread with priority");
});
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
线程的停止
不建议使用stop()方法停止线程,而是通过标志位控制:

class StoppableThread implements Runnable {
private volatile boolean stopRequested = false;
public void run() {
while (!stopRequested) {
System.out.println("Thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void requestStop() {
stopRequested = true;
}
}
public class Main {
public static void main(String[] args) {
StoppableThread stoppable = new StoppableThread();
Thread thread = new Thread(stoppable);
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stoppable.requestStop();
}
}






