时间:2026-04-12 09:43
人气:
作者:admin
多线程程序在更低一层扩展了多任务的概念:单个程序看起来在同时完成多个任务。每个任务在一个线程(thread)中执行,线程是控制线程的简称。如果一个程序可以同时运行多个线程,则称这个程序是多线程的(multithreaded)。
线程的创建有三种方式:
public class ThreadTest {
private static final int STEP = 100;
public static void main(String[] args) {
MyJob job = new MyJob();
job.start();
for (int i = 0; i < STEP; i++) {
System.out.println("main run: " + i);
}
}
}
class MyJob extends Thread {
private static final int STEP = 100;
@Override
public void run() {
for (int i = 0; i < STEP; i++) {
System.out.println("job run: " + i);
}
}
}
public class RunnableTest {
private static final int STEP = 100;
public static void main(String[] args) {
MyAnotherJob job = new MyAnotherJob();
Thread t = new Thread(job);
t.start();
for (int i = 0; i < STEP; i++) {
System.out.println("main run: " + i);
}
}
}
class MyAnotherJob implements Runnable {
private static final int STEP = 100;
@Override
public void run() {
for (int i = 0; i < STEP; i++) {
System.out.println("job run: " + i);
}
}
}
Callable一般用于有返回结果的非阻塞的执行方法
同步非阻塞
Callable<V> 接口import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyTask implements Callable<String> {
private final long duration; // 模拟耗时操作的时间(毫秒)
public MyTask(long duration) {
this.duration = duration;
}
@Override
public String call() throws Exception {
System.out.println("任务开始执行...");
Thread.sleep(duration); // 模拟耗时操作
return "任务完成,耗时 " + duration + " 毫秒";
}
}
public class CallableExample {
public static void main(String[] args) {
Callable<String> callable = new MyTask(2000);
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask, "MyThread");
thread.start();
System.out.println("主线程继续执行其他任务...");
try {
String result = futureTask.get();
System.out.println("线程返回结果: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 优点 | 缺点 | |
|---|---|---|
| 继承Thread类 | 实现简单,可以直接使用Thread类中的方法 | 不能再继承其他类,扩展性较差 |
| 实现Runnable接口 | 扩展性强,实现接口的同时可以继承其他类 | 编程比较复杂,不能使用Thread类的其他方法 |
| 实现Callable接口 | 扩展性强,实现接口的同时可以继承其他类 | 编程比较复杂,不能使用Thread类的其他方法 |
【从0到1构建一个ClaudeAgent】协作-Agent团队