1.多线程实现的两种方式
1.1 extends Thread(继承的方式)
public class MyThread extends Thread {public void run() {/* 为了方便测试 */// try {// Thread.sleep(1000);// } catch (InterruptedException e) {// e.printStackTrace();// }System.out.println(Thread.currentThread().getName() + "正在执行。。。");System.out.println("发送注册成功的邮件");}}
1.2 implements Runnable(实现接口的方式)
public class MyThread implements Runnable {@Overridepublic void run() {/* 为了方便测试 */// try {// Thread.sleep(1000);// } catch (InterruptedException e) {// e.printStackTrace();// }System.out.println(Thread.currentThread().getName() + "正在执行。。。");}}
2.线程池的应用
案例需求:对于注册成功的用户,要给其发一份注册成功的邮件。(如果传统代码的同步执行会浪费很长时间。所以采用多线程的方法)
public class ThreadPools {public static void main(String[] args) throws Exception {System.out.println("注册成功!");//创建一个可重用固定线程数的线程池ExecutorService pool = Executors.newCachedThreadPool();//创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口Thread t1 = new MyThread();//将线程放入池中进行执行pool.execute(t1);//关闭线程池pool.shutdown();System.out.println("返回前端页面");}}
其中MyThread这个类采用了1.1的方式。效果如下:
