概念:
线程的创建:
通过new Thread()
Thread T1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("守护线程T1在执行");
}
}
});
线程的实现方式:
通过实现Runnable接口,重写run()方法,实现线程:
Thread T1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("守护线程T1在执行");
}
}
});
继承Thread类,重写run()方法,实现线程
static class AddThread extends Thread {
ReentrantLock lock = test2.reentrantLock;
public void run() {
for (int i = 0; i < 10000; i++) {
// Counter.count2.incrementAndGet();//自增1
// 通过ReentrantLock加锁
lock.lock();
try {
Counter.count += 1;
} finally {
// 通过ReentrantLock释放锁
lock.unlock();
}
}
}
}
实现Callable接口,重写call()方法,实现线程
// 创建callable
MyCallAble callAble1 = new MyCallAble(1, 50);
MyCallAble callAble2 = new MyCallAble(51, 100);
// 创建Future=>将callable转化为runable
FutureTask<Integer> future1 = new FutureTask<>(callAble1);
FutureTask<Integer> future2 = new FutureTask<>(callAble2);
Thread thread1 = new Thread(future1);
Thread thread2 = new Thread(future2);
thread2.start();
thread1.start();
//MyCallAble 类
static class MyCallAble implements Callable<Integer> {
private int begin, end;
public MyCallAble(int begin, int end) {
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int it = 0;
for (int i = begin; i <= end; i++) {
it += i;
}
return it;
}
}
通过线程池创建并管理线程,需要使用线程时,向线程池提交线程任务,由线程池分配空闲线程去执行线程任务
// ThreadPoolExecutor:线程池类
// Executors类:工具类,用于创建各种线程
// ExecutorService:定义线程池的行为
// 创建线程
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 提交线程任务
for(int i=0;i<=10;i++){
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程池中的"+Thread.currentThread().getName()+"开始执行————————");
}
});
}
// 关闭线程池
executorService.shutdown();
线程的优先级:
默认为5,优先级最低为1,最高为10,具体执行顺序和优先级关系不大,还是操作系统分配时间片
线程状态
此处是针对java中的原码中的状态的解释,进入runable阶段可以分为两种状态:可运行状态,表示时刻准备着等分配,还有一种就是已经运行的状态
线程的中断
通过interrupt()方法,改变中断状态值,并通过抛出一个InterruptedException异常,中断线程执行
线程的让出
基于操作系统的线程抢占模型,线程会通过yield( ) 实现当前线程对CPU时间的让出