Java中创建线程的方法

继承Thread方法

  • start方法只能调用一次
  • run方法自动调用不能手动
public class MyThread extends Thread {
  @Override
  public void run(){
      for(int i=0;i<10000;i++){
          try {
              Thread.sleep(1000);
              print("I am the new thread!");
          }catch (InterruptedException e){
              e.printStackTrace();
          }
      }
  }
}

实现Runnable接口

public class MyThread2 implements Runnable {
  @Override
  public void run() {
      for(int i=0;i<10000;i++){
          try {
              Thread.sleep(1000);
              print("I am the thread2!");
          }catch (InterruptedException e){
              e.printStackTrace();
          }
      }
  }
}

实现Callable接口

public class MyThread3 implements Callable<String> {
  @Override
  public String call() throws Exception {
      for (int i = 0; i < 10000; i++) {
          try {
              Thread.sleep(1000);
              print("I am the thread3!");
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
      return "返回";
  }
}

线程池

*固定大小线程池

private void test1(){ ExecutorService ex= Executors.newFixedThreadPool(5); for(int i=0;i<5;i++){ ex.submit(() -> { System.out.print(“I am test1”); System.out.print(“I am test1”); }); } ex.shutdown();//正在运行的线程运行完,线程池就关闭 }
  • 单线程池
     private void test2(){
         ExecutorService ex= Executors.newSingleThreadExecutor();
         for(int i=0;i<5;i++){
             ex.submit(() -> System.out.print("I am test 2"));
         }
         ex.shutdown();
     } `` 缓存线程池 ```   private void test3(){
  ExecutorService ex= Executors.newCachedThreadPool();
  for(int i=0;i<5;i++){
      ex.submit(() -> System.out.print("I am test 3"));
  }
  ex.shutdown();   } 

主线程

public static void main(String[] args){
  //方法一
  MyThread myThread=new MyThread();
  myThread.start();
  //方法二
  new Thread(new MyThread2()).start();
  Callable<String> callable=new MyThread3();
  //方法三
  FutureTask<String> futureTask=new FutureTask<>(callable);
  new Thread(futureTask).start();
  //方法四
  Solution190215 solution190215=new Solution190215();
  solution190215.test1();
  solution190215.test2();
  solution190215.test3();
  //主线程
  for(int i=0;i<10000;i++){
      try {
          Thread.sleep(1000);
          print("I am the main thread!");
      }catch (InterruptedException e){
          e.printStackTrace();
      }
  }   } 

参考

posted @ 2021-09-07 13:24  -Rocky-  阅读(70)  评论(0编辑  收藏  举报