一、线程的创建方式(四种)
1、继承Thread类
例:public class TestThread extends Thread{
@Override
public void run() {
System.out.println("需要线程干的事情写在run()中");
}
}
public class Test {//在此类中使用创建的线程
public static void main(String[] args) {
TestThread t1 = new TestThread();
t1.start();//启动线程
}
}
2、实现Runnable接口
class TestThread implements Runnable{
@Override
public void run() {
System.out.println("需要线程干的事情写在run()中");
}
}
public class Test {
public static void main(String[] args) {
TestThread t1 = new TestThread();
Thread th1=new Thread(t1);
th1.start();//启动线程
}
}
方式1和方式2的对比:
方式1
优点:代码相对简单,容易理解;
缺点:继承的单一性,继承Thread类仅仅只为作为线程使用,不能继承其它类,一个类对应一个线程, 不够灵活。
方式2
优点:解决了方式1中的单一继承的弊端,一个类可以对应被多个线程共用,较为灵活
缺点:实现Runnable接口后仍需创建一个线程对象,将实现接口的类的对象作为参数传给Thread类。
3、实现Callable接口(JDK5.0新增)
public class HelloWord {
public static void main(String[] args) {
TestThread t1=new TestThread();
FutureTask futureTask = new FutureTask(t1);
new Thread(futureTask).start();
try {
//get()方法为FutureTask构造方法中的 TestThread对象实现的Callable接口中重写的Call方法的返回值
Object sum= futureTask.get();
System.out.println(sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class TestThread implements Callable {
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i <10 ; i++) {
sum+=i;
}
return sum;
}
}
方式2和方式3对比
相同点:都是实现接口的方式,实现Runnable接口重写run()方法,实现Callable接口重写call()方法。
不同点:
1、Callable是带有返回值的。
2、Callable的覆盖方法可以抛出异常。
3、支持泛型的返回值
4、需要借助FutureTask类,比如获取返回结果
4、使用线程池创建线程(JDK5.0新增)
public class HelloWord {
public static void main(String[] args) {
TestThread t1=new TestThread();
//1、创建固定线程数量的线程池
ExecutorService executorService1= Executors.newFixedThreadPool(10);
//2、创建一个可以根据需要创建新线程的线程池
ExecutorService executorService2=Executors.newCachedThreadPool();
//3、创建只有一个线程的线程池
ExecutorService executorService3=Executors.newSingleThreadExecutor();
//4、创建一个创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
ExecutorService executorService4=Executors.newScheduledThreadPool(10);
//实现Callable接口,则用executorService.submit(t1),实现Runnable接口则用executorService.execute(t1),
Future submit = executorService1.submit(t1);
try {
System.out.println(submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class TestThread implements Callable {
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i <10 ; i++) {
sum+=i;
}
return sum;
}
}
使用线程池创建线程相对于普通方式创建线程的优势:
不适用线程池:经常创建和销毁线程,使用特别大的资源,比如并发情况下的线程对性能影响很大。
使用线程池:提前创建好多个线程放在线程池中,需要使用时直接从线程池中获取,使用完后放回线程池中,可以避免反复的创建和销毁、实现重复利用。
优势:
1、提高响应速度(减少创建线程所花费的时间)
2、降低资源消耗(可以重复利用线程池中的线程,不需要每次都重新创建)
3、便于管理线程
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
…