常用有以下几种方式
-
继承Thread类
-
实现Runnable接口,可使用lambda简洁写法
-
实现Callable接口
-
线程池创建
一,继承Thread类
继承Thread类,重写run()方法
class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
@Test
public void threadTest() {
MyThread myThread = new MyThread();
myThread.start();
}
二,实现Runnable接口
实现Runnable接口,重写run()方法
class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
@Test
public void threadTest() {
Thread thread2 = new Thread(new MyThread2());
thread2.setName("MyThread2");
thread2.start();
}
简洁写法:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
lambda写法:
new Thread(()-> {
System.out.println(Thread.currentThread().getName());
}).start();
三,实现Callable接口
实现Callable接口,重写call()方法
class MyThread3 implements Callable<String> {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
}
@Test
public void threadTest() {
FutureTask<String> futureTask = new FutureTask<>(new MyThread3());
new Thread(futureTask).start();
try {
String futureName = futureTask.get();
System.out.println(futureName);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
四,线程池创建
Executors创建线程池,只需要调用Executors中相应的便捷方法即可。
newFixedThreadPool(int nThreads)
创建固定大小的线程池
newSingleThreadExecutor()
创建只有一个线程的线程池
newCachedThreadPool()
创建一个不限线程数上限的线程池,任何提交的任务都将立即执行
向线程池提交的任务有两种
Runnable和Callable
@Test
public void threadTest() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
for(int i = 0; i < 10; i++){
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
//do something
}
});
}
评论区