liubaihui

实现方式:

1,继承Thread类

public class ThreadTest extends Thread {
@Override
 public void run() {
 System.out.println(Thread.currentThread().getName());
}
 public static void main(String[] args) {
    ThreadTest test=new ThreadTest();
     test.start();
}
}

2,实现一个Runable接口

public class ThreadTest implements Runnable {
 @Override
public void run() {
// TODO Auto-generated method stub

}
public static void main(String[] args) {
ThreadTest t1=new ThreadTest();
Thread thread=new Thread(t1);
thread.start();
}

}

3,线程池实现方式Executors

//创建一个可重用固定线程数的线程池
ExecutorService pool = Executors. newSingleThreadExecutor();
//创建一个可重用固定线程数的线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建一个可重用固定线程数的线程池
ExecutorService pool = Executors.newCachedThreadPool();

例如:

//创建实现了Runnable接口对象
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        //将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        //关闭线程池
        pool.shutdown();
    }

 

相关文章:

  • 2022-02-09
  • 2021-11-06
  • 2021-06-17
  • 2021-07-12
  • 2021-12-28
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2021-11-03
  • 2021-08-25
  • 2021-11-05
  • 2021-12-03
  • 2021-10-26
  • 2019-07-11
  • 2022-01-28
相关资源
相似解决方案