繼承Thread類 實現Runnable介面 匿名內部類的兩種寫法 基於java.util.concurrent.Callable工具類的實現,帶返回值 基於java.util.Timer工具類的實現 基於java.util.concurrent.Executors工具類,基於線程池的實現 更多信息 ...
繼承Thread類
public class ExtendsThreadTest extends Thread {
@Override
public void run() {
System.out.println("thread is running!");
}
public static void main(String[] args) {
ExtendsThreadTest et1 = new ExtendsThreadTest();
et1.start();
}
}
實現Runnable介面
public class RunnableTest implements Runnable{
@Override
public void run() {
System.out.println("thread is running!");
}
public static void main(String[] args) {
Thread t1 = new Thread(new RunnableTest());
t1.start();
}
}
匿名內部類的兩種寫法
public class App {
public static void main(String[] args){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 is running!");
}
}){}.start();
new Thread(){
@Override
public void run(){
System.out.println("thread2 is running!");
}
}.start();
}
}
基於java.util.concurrent.Callable工具類的實現,帶返回值
public class CallableTest {
public static void main(String[] args) throws Exception {
Callable<Integer> call = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("thread is running!");
return 1;
}
};
FutureTask<Integer> task = new FutureTask<>(call);
Thread t = new Thread(task);
t.start();
}
}
基於java.util.Timer工具類的實現
public class TimerTest {
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("thread is running!");
}
}, new Date());
}
}
基於java.util.concurrent.Executors工具類,基於線程池的實現
public class ThreadPoolTest {
public static void main(String[] args) {
// 創建線程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
while(true) {
threadPool.execute(new Runnable() { // 提交多個線程任務,並執行
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running ..");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
也歡迎關註我的公眾號:yizhuxiaozhan,二維碼: