public class MyThread extends Thread {
@Override
public void run() {
System.out.println("my thread");
}
// public static void main(String[] args) {
// MyThread myThread = new MyThread();
// myThread.start();
// }
public static void main(String[] args) {
// 也支持 lambda 表达式
new Thread(() -> {
System.out.println("my runnable11");
}).start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("my runnable1");
}
// public static void main(String[] args) {
// Thread thread = new Thread(new MyRunnable());
// thread.start();
//
// // 也支持 lambda 表达式
// Thread thread1 = new Thread(() -> {
// System.out.println("my runnable2");
// });
// thread1.start();
// }
public static void main(String[] args) {
// 也支持 lambda 表达式
new Thread(() -> {
System.out.println("my runnable3");
}).start();
}
}
public class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable(100);
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
int result = futureTask.get();
System.out.println("1到100的和为:" + result);
}
}
public class TempThread implements Runnable{
@Override
public void run() {
// 打印正在执行的缓存线程信息
System.out.println(Thread.currentThread().getName() + "正在被执行");
try {
// sleep一秒保证3个任务在分别在3个线程上执行
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestThreadPoolExecutor {
public static void main(String[] args) {
// 创建数组型缓冲等待队列
BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
// ThreadPoolExecutor:创建自定义线程池,池中保存的线程数为3,允许最大的线程数为6
//非核心线程空闲后可以存活的时间,时间单位,阻塞队列,线程工厂
ThreadPoolExecutor tpe =
new ThreadPoolExecutor(
3,
6,
50,
TimeUnit.MILLISECONDS, bq);
// 创建3个任务
Runnable t1 = new TempThread();
Runnable t2 = new TempThread();
Runnable t3 = new TempThread();
// 3个任务在分别在3个线程上执行
tpe.execute(t1);
tpe.execute(t2);
tpe.execute(t3);
// 关闭自定义线程池
tpe.shutdown();
}
}