线程:cpu调度的最小单位
一个进程中至少包含一条线程:主线程
主线程系统创建的
java中主线程的入口:public static void main(String[]args){}
使用线程的4个步骤:
1、定义一个线程。指明所有执行的代码;
2、创建线程对象;
3、启动线程;
4、终止线程
java中创建线程的方式:
1、创建Thread的子类:重写Thread的run方法
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
System.out.println("sub"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
}
2、匿名内部类创建Thread的对象:重写Thread的run方法
public class ThreadTest {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
System.out.println("sub"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
3、创建Runnable接口对象,作为Thread的构造参数传入
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
System.out.println("sub"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
Thread thread = new Thread(new MyThread());
thread .start();
}
}
线程池
- 固定线程池:创建固定数量线程数,有闲置可申请,没有则需等待
ExecutorService pool = Executors.newFixedThreadPool(int size);
- 缓存线程池:初始化不创建任何线程,根据需要不限制的创建,当线程被闲置到一定阀值会被回收
ExecutorService pool = Executors.newCachedThreadPool();
- 单线程池:只维护一条线程的线程池
ExecutorService pool = Executors.newSingleThreadExecutor();
- 通过Runnable/Callable对象传入到线程池的submit方法完成任务
无返回值pool.submit(Runnable task); 有返回值Future<T> future = pool.submit(Callable<T> call);
- 计划线程池:根据需要在指定时间执行或以固定的周期或固定延时重复执行的线程池
ScheduledExecutorService schedulePool = Executors.newScheduledThreadPool();
- 释放线程池
pool.shutdown();
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i <3 ; i++) {
final int _i = i;
pool.submit(new Runnable() {
@Override
public void run() {
for (int j = 0; j <10; j++) {
System.out.println("Thread-"+_i+"\t"+j);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
pool.shutdown();