下面从基础概念 → 常见用法 → 实践示例 → 注意事项,系统地讲一下 Java 多线程的实践方式。
Threadclass MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
public class Test {
public static void main(String[] args) {
new MyThread().start();
}
}
✅ 简单
❌ 不支持多继承,不推荐日常使用
Runnable(推荐)class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
public class Test {
public static void main(String[] args) {
new Thread(new MyTask()).start();
}
}
✅ 更灵活(可配合线程池)
Callable + Future(有返回值)import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<String> future = pool.submit(() -> "result");
System.out.println(future.get());
pool.shutdown();
}
}
✅ 能返回结果 / 抛异常
不要手动频繁 new Thread,应使用线程池。
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.execute(() -> {
System.out.println("task");
});
pool.shutdown();
推荐手动创建(更可控):
new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
synchronizedpublic synchronized void add() {
count++;
}
或代码块:
synchronized (this) {
count++;
}
LockLock lock = new ReentrantLock();
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
✅ 更灵活(可中断、超时)
AtomicInteger count = new AtomicInteger();
count.incrementAndGet();
wait / notifysynchronized (obj) {
obj.wait();
obj.notify();
}
CountDownLatchCyclicBarrierSemaphoreBlockingQueueList<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futures.add(pool.submit(task));
}
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
shutdown()java.util.concurrent)如果你愿意,我可以:
你现在是学习阶段还是项目实战?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。