多线程使用
- 创建子线程并运行
public class ThreadTest {
private static class MyTestThread extends Thread {
@Override
public void run() {
System.out.println("MyTestThread run");
}
}
public static void main(String[] args) {
new MyTestThread().start();
}
}
问题:1. 没有多继承,只能继承Thread类;2. 任务和线程没有分离,当多个线程需要执行同一个任务时,需要多份任务代码 解决办法:改用Runnable
- 使用Runnable
private static class MyTask implements Runnable {
@Override
public void run() {
System.out.println("threadName="+Thread.currentThread().getName() + ":MyTestThread run");
}
}
public static void main(String[] args) {
MyTask myTask = new MyTask();
new Thread(myTask).start();
new Thread(myTask).start();
}
问题:无法获取返回值 解决办法:使用FutureTask
- 使用FutureTask
private static class MyCall implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 1314;
}
}
public static void main(String[] args) {
FutureTask<Integer> integerFutureTask = new FutureTask<>(new MyCall());
new Thread(integerFutureTask).start();
try {
Integer result = integerFutureTask.get();
System.out.println(result);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
线程通知与等待
[[多线程编程]]