实现方式:
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();
例如:
4,线程的生命周期
线程状态:创建new thread,就绪(start),运行(run),阻塞状态,终止