方法一:继承Thread类,重写run方法,直接调用start方法开启线程。
/** * 继承Thread类,直接调用start方法开启线程。 * @author LuRenJia */ public class LeaningThread extends Thread { public void run() { for (int i = 0; i < 20; i++) { System.out.println("可是这和我是一个冷酷的复读机又有什么关系呢?"); } } public static void main(String[] args) { LeaningThread Lt = new LeaningThread(); Lt.start(); } }
方法二:实现Runable接口,重写run方法,通过Thread类调用start开启线程。
/** * 实现Runnable接口来实现多线程,通过代理 * @author LuRenJia */ public class LeaningRunnable implements Runnable { public void run() { for (int i = 0; i < 20; i++) { System.out.println("可是这和我是一个冷酷的复读机又有什么关系呢?"); } } public static void main(String[] args) { new Thread(new LeaningRunnable()).start(); } }
方法三:实现Callabler接口,重写call方法,通过ExecutorService类创建服务,调用其submit方法开启线程,通过其shutdown方法关闭服务。
/** * 实现Callable接口来实现多线程 * @author LuRenJia */ public class LeaningCallable implements Callable<String> { private String name; public LeaningCallable(String name) { this.name = name; } // 重写call方法,线程执行的内容,返回值通过get方法获取 @Override public String call() throws Exception { for (int i = 0; i < 20; i++) { System.out.println(name + ":" + "可是这和我是一个冷酷的复读机又有什么关系呢?"); } return name; } public static void main(String[] args) { LeaningCallable lc1 = new LeaningCallable("线程一"); LeaningCallable lc2 = new LeaningCallable("线程二"); LeaningCallable lc3 = new LeaningCallable("线程三"); // 创建执行服务 ExecutorService server = Executors.newFixedThreadPool(3); // 提交执行 Future<String> result1 = server.submit(lc1); Future<String> result2 = server.submit(lc2); Future<String> result3 = server.submit(lc3); try { String temp = result1.get();// 获取返回值 System.out.println("返回值是:" + temp); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } // 关闭服务 server.shutdown(); } }
快捷创建:使用lambda表达式快速创建简单线程。
/** * lambda表达式:父类接口中只有一个方法待实现时,可以使用lambda表达式简化代码 * 1.标准形式: * ()->{ * * } * 2.等价于一个实现了接口的之、子类。 * * Thread类实现了Runnable接口,且此接口只有一个run方法待实现。 * @author LuRenJia * */ public class LeaningLambda2 { public static void main(String[] args) { new Thread(new Runnable(){ @Override public void run() { for(int i =0;i<100;i++) { System.out.println("可是这和我是一个冷酷的复读机又有什么关系呢?"); } } }).start(); //使用lambda表达式快速创建简单线程 new Thread(()->{ for(int i =0;i<100;i++) { System.out.println("这触及到我的知识盲区了!"); } }).start(); } }