多线程创建方式一:继承Tread类

  1. package com.kemoon.www;
  2. public class Test extends Thread{
  3. // 重写run方法
  4. public void run()
  5. {
  6. for (int i = 0; i < 20; i++) {
  7. System.out.println("子线程"+i);
  8. }
  9. }
  10. public static void main(String[] args) {
  11. Test test = new Test();
  12. test.start();
  13. for (int i = 0; i < 20; i++) {
  14. System.out.println("main Thread"+i);
  15. }
  16. }
  17. }

多线程创建方式二:实现runable接口

  1. package com.kemoon.www;
  2. public class Test implements Runnable{
  3. // 实现run方法
  4. public void run()
  5. {
  6. for (int i = 0; i < 20; i++) {
  7. System.out.println("子线程"+i);
  8. }
  9. }
  10. public static void main(String[] args) {
  11. Test test = new Test();
  12. new Thread(test).start();
  13. for (int i = 0; i < 2000; i++) {
  14. System.out.println("main Thread"+i);
  15. }
  16. }
  17. }

多线程创建方式三:实现callable接口

  1. package com.kemoon.www;
  2. import java.util.concurrent.*;
  3. /*
  4. 线程创建方式: 实现callable接口
  5. 1.可以定义返回值
  6. 2.可以抛出异常
  7. */
  8. public class TestCallable implements Callable<Boolean> {
  9. private String name;
  10. public TestCallable(String name){
  11. this.name=name;
  12. }
  13. // 执行体
  14. public Boolean call(){
  15. for (int i = 0; i < 20; i++) {
  16. System.out.println(this.name);
  17. }
  18. return true;
  19. }
  20. public static void main(String[] args) throws ExecutionException, InterruptedException {
  21. TestCallable t1 = new TestCallable("t1");
  22. TestCallable t2 = new TestCallable("t2");
  23. TestCallable t3 = new TestCallable("t3");
  24. // 创建执行服务
  25. ExecutorService ser = Executors.newFixedThreadPool(3);
  26. // 提交执行
  27. Future<Boolean> r1 = ser.submit(t1);
  28. Future<Boolean> r2 = ser.submit(t2);
  29. Future<Boolean> r3 = ser.submit(t3);
  30. // 获取结果
  31. boolean rs1=r1.get();
  32. boolean rs2=r2.get();
  33. boolean rs3=r3.get();
  34. ser.shutdownNow();
  35. }
  36. }

创建线程池

  1. package com.kemoon.www;
  2. public class TestPool{
  3. public static void main(String[] args){
  4. // 创建服务,创建线程池
  5. ExecutorService service = Executors.newFixedThreadPool(10);
  6. // 执行
  7. service.execute(new Test());
  8. service.execute(new Test());
  9. service.execute(new Test());
  10. service.execute(new Test());
  11. // 关闭链接
  12. service.shutdown();
  13. }
  14. }
  15. class Test implements Runnable{
  16. // 实现run方法
  17. public void run()
  18. {
  19. System.out.println("线程"+i);
  20. }
  21. }