Java线程的创建方式有以下几种:
class MyThread extends Thread {
public void run() {
// 线程执行的任务
}
}
MyThread thread = new MyThread();
thread.start();
class MyRunnable implements Runnable {
public void run() {
// 线程执行的任务
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
Thread thread = new Thread() {
public void run() {
// 线程执行的任务
}
};
thread.start();
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 线程执行的任务,返回一个结果
return 1;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new MyCallable());
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(new Runnable() {
public void run() {
// 线程执行的任务
}
});