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("Runnable thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // 启动线程
}
}
使用 Lambda 表达式简化
如果线程逻辑简单,可以直接使用 Lambda 表达式实现 Runnable 接口。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Lambda thread is running");
});
thread.start();
}
}
线程的常用方法
start():启动线程,调用run()方法。sleep(long millis):使线程暂停指定毫秒数。join():等待线程执行完毕。interrupt():中断线程的执行。
线程同步
多线程共享资源时可能出现竞争问题,可以通过 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) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}
线程池的使用
通过线程池可以高效管理线程资源,避免频繁创建和销毁线程的开销。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}






