创建线程的方式
- 继承Threead类
- 实现Runnable接口
- 通过Callable接口和ExecutorService实现带有返回值的线程
-
使用线程池
- 继承Threead类
public class MyThreads{
/**
* step1 具体方法
*/
public class MyThread extends Thread{
@Override
public void run() {
System.out.println("继承方式创建线程");
}
}
public void main(String[] args) {
/**
* step 2 创建对象
*/
MyThread newThread = new MyThread();
/**
* step 3 使用线程
*/
newThread.start();
}
}
- 实现Runnable接口
/**
* 实现Runnable接口创建线程
* @author dby
* @since time
*/
public class MyThreads2 implements Runnable{
@Override
public void run() {
System.out.println("实现接口创建线程");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyThreads2());
thread.start();
}
}
- 通过Callable接口和ExecutorService实现带有返回值的线程
/**
* 实现Runnable接口创建线程
* @author dby
* @since time
*/
public class MyThreads3 implements Callable {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public String call() throws Exception {
//具体逻辑动作
return "返回值";
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Future> li = new ArrayList<>();
for (int i = 0; i < 5; i++) {
MyThreads3 threads3 = new MyThreads3();
Future submit = pool.submit(threads3);
li.add(submit);
}
pool.shutdown();
for (Future future : li) {
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
- 使用线程池
/**
* 使用线程池创建线程
* @author dby
* @since time
*/
public class MyThreads4{
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> System.out.println("使用线程池创建线程"));
}
}