···
package com.yu.exercise;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadDemo {
public static void main(String[] args) {
//使用runnable接口实现线程的创建
new Thread(
new Runnable() {
@Override
public void run() {
System.out.println("只有接口才能使用匿名类部类");
}
}
).start();
//使用继承Thread线程类来创建线程
MyThread aThread = new MyThread();
aThread.start();
// Class clazz=Thread.class;
// Field[] fields = clazz.getDeclaredFields();
// for(Field f:fields) {
// System.out.println(f);
// }
//使用Callable接口和Fulture创建线程
/*使用匿名类部类实现Callable接口带用返回值的方法,作为参数传入Runnable的实现类FutureTask构造函数中
构造一个FutureTask对象,然后通过Thread类(futureTask)创建线程,再使用FutureTask对象获取callable对象的返回值
*/
Callable callable = new Callable() {
@Override
public Integer call() throws Exception {
int sum=0;
for (int i = 1; i <101 ; i++) {
sum+=i;
}
return sum;
}
};
FutureTask integerFutureTask = new FutureTask<>(callable);
new Thread(integerFutureTask).start();
try {
System.out.println(integerFutureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//使用线程池创建线程不能避免其中的默认实现Executors
ExecutorService pool = Executors.newFixedThreadPool(8);
//往线程池中提交任务,主要有两种方法,execute()和submit()
for(int i=0;i<8;i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//使用Lambda表达式代替runnable的实现类内部类
pool.execute(()->{
System.out.println("当前线程为:"+Thread.currentThread().getName());
});
}
//使用ThreadPoolExecutor手动指定参数,指定核心线程池的大小、最大线程池的数量、保持存活的时间、等待队列容量的大小
//ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, 0, 0, null, null);
}
}
class MyThread extends Thread{
public void run(){
System.out.println(“使用直接继承Thread类来创建线程”);
}
}