Java 线程实现
- 继承Thread
- 实现Runnable
- 有返回值使用Callable
package com;
import com.entity.Data;
import java.util.*;
import java.util.concurrent.*;
public class ThreadTest {
static ArrayList<Integer> list;
static Vector<Integer> vector;
public static void main(String[] args) {
ConcurrentHashMap map = new ConcurrentHashMap();
// 固定大小线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
// 无固定大小灵活创建回收线程
// ExecutorService threadPool = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(new Date().getTime());
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// Callable可以在任务结束的时候提供一个返回值,Runnable无法提供这个功能
// Callable的call方法分可以抛出异常,而Runnable的run方法不能抛出异常。
Callable callable = new Callable() {
@Override
public Object call() throws Exception {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Long l = new Date().getTime();
if ( l%3==0) {
throw new Exception("测试测试");
}
return new Date().getTime();
}
};
//继承Thread 启动
Mythread mythread = new Mythread();
mythread.start();
//实现runnable 启动
Thread threadRun = new Thread(runnable);
threadRun.start();
List <Future<Long>> list = new ArrayList<>();
// 线程池方式
// 2. submit()有返回值,而execute()没有;
// 3. submit()可以进行Exception处理;
for (int i=0; i<30; i ++ ) {
// threadPool.execute(runnable);
list.add(threadPool.submit(callable));
}
// 关闭线程池
threadPool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从Future对象上获取任务的返回值,并输出到控制台
try {
System.out.println(">>>" + f.get().toString()); //OPTION + return 抛异常
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
static class Mythread extends Thread{
@Override
public void run() {
System.out.println(new Date().getTime());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果