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() {
// 線程執行的任務
}
});