线程,一直都是非常基础且重要的知识点,因为,在多线程下,什么都可能发生。
线程生命周期
线程是一个动态执行到过程,从出生,到死亡。
- New(创建,初始化状态)
- Runnable(可运行/运行状态)
- Blocked(阻塞状态)
- Waiting(无时间限制的等待状态)
- Timed_Waiting(有时间限制的等待状态)
- Terminated(终止状态)
线程创建
1、继承Thread类
public class MyThread extends Thread {
public MyThread() {
}
public void run() {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread()+":"+i);
}
}
public static void main(String[] args) {
MyThread thread1=new MyThread();
MyThread thread2=new MyThread();
MyThread thread3=new MyThread();
thread1.start();
thread2.start();
thread3.start();
}
}
2.覆写Runnable()接口
public class MyThread implements Runnable{
public static int count=20;
public void run() {
while(count>0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-当前剩余票数:"+count--);
}
}
public static void main(String[] args) {
MyThread Thread1=new MyThread();
Thread thread1=new Thread(Thread1,"线程1");
Thread thread2=new Thread(Thread1,"线程2");
Thread thread3=new Thread(Thread1,"线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
3,使用线程池
FixThreadPool(int n); 固定大小的线程池
SingleThreadPoolExecutor :单线程池
CashedThreadPool(); 缓存线程池