多线程的创建方式
多线程的创建方式共4中,包括:
1.继承Thread类方式
2.实现Runnable接口方式
3.实现Callable接口方式(jdk5.0新增)
4.线程池(jdk5.0新增)
一、继承Thread类
1.创建一个类继承于Thread类
2.重写新创建的类中的run()方法(该线程需要实现的功能的具体方法)
3.创建新线程的子类对象(创建多个线程需要多次创建新的子类对象)
4.子类对象调用start()方法
注意:不能直接掉run(),否则就不是多线程了。
示例代码:
package JAVA; class MyThread extends Thread{ @Override public void run() { for (int i = 0; i <100 ; i++) { if (i%2==0){ System.out.println(i); } } } } public class ThreadTest { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } }
二、实现了Runnable接口方式
1.创建一个实现了Runnable接口的类
2.实现类去实现Runnable中的抽象方法:run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5.通过Thread类的对象调用start()
示例代码:
class Test implements Runnable{ @Override public void run() { for (int i = 1; i <= 100; i++) { if (i%2==0){ System.out.println(i); } } } } public class ThreadTT { public static void main(String[] args) { Test t = new Test(); Thread t1 = new Thread(t); t1.start(); } }
三、实现Callable接口方式
1.创建一个实现Callable的实现类
2.实现call方法,将此线程需要执行的操作声明在call()中
3.创建Callable接口实现类的对象
4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
6.获取Callable中call方法的返回值
示例代码:
class Test implements Callable { @Override public Object call() throws Exception { int sum=0; for (int i = 1; i <=100 ; i++) { if (i%2==0){ sum+=i; } } return sum; } } public class ThreadTT { public static void main(String[] args) { Test t = new Test(); FutureTask futureTask = new FutureTask(t); Thread thread = new Thread(futureTask); thread.start(); try { Object sum=futureTask.get();//接收返回值 System.out.println(sum); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大:
1. call()可以返回值的。
2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
3. Callable是支持泛型的
四、使用线程池方式
1. 提供指定线程数量的线程池
2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
3.关闭连接池
示例代码:
class Test1 implements Runnable { @Override public void run() { for (int i = 1; i <=100 ; i++) { if (i%2==0){ System.out.println(Thread.currentThread().getName()+":"+i); } } } } class Test2 implements Runnable{ @Override public void run() { for (int i = 1; i <=100 ; i++) { if (i%2!=0){ System.out.println(Thread.currentThread().getName()+":"+i); } } } } public class ThreadTT { public static void main(String[] args) { //设置线程池的线程数 ExecutorService service = Executors.newFixedThreadPool(2); service.execute(new Test1()); service.execute(new Test2()); service.shutdown();//关闭连接池 } }
使用线程池的好处:
1.提高响应速度(减少了创建新线程的时间)
2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3.便于线程管理:
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没任务时最多保持多长时间后会终止
原文:https://www.cnblogs.com/javasds/p/12297668.html