进程是资源分配的最小单位,线程是最小调度单位
并发:轮流交替做多件事情
单核cpu下,多线程不能实际提高程序运行效率,只是不同线程轮流使用cpu
同步:需要等待结果返回,才能继续运行后面的代码
异步:不需要等待结果返回,继续运行后面的代码
线程调度机制
new Thread(() -> FileReader.read("xwfdwf")).start();
log.debug("do other things...");
public static void main(String[] args) {
// 默认有一个主线程
// 创建线程
// 1.Thread的匿名子类的对象
Thread t = new Thread(){
@Override
public void run() {
log.debug("cwfcwfcwcwccx");
System.out.println("cwcw");
}
};
// 启动
t.start();
log.debug("main=================");
System.out.println("main");
}
执行出来的顺序是随机的
// 创建线程的方式
Thread s = new Thread(() -> System.out.println("cwcw"));
// 返回结果是Integer
FutureTask<Integer> fu = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
log.debug("PPPPP===");
return 100;
}
});
Thread t = new Thread(fu,"t");
t.start();
System.out.println(fu.get()); // 100
给线程分配一个栈内存,线程的栈内存是相互独立的,每个线程有自己独立的栈
方法,栈帧(局部变量表,返回地址)
线程上下文切换:因为以下一些原因导致cpu不再执行当前线程,转而执行另一个线程
线程的cpu时间片用完
垃圾回收
有更高优先级的线程需要运行
线程自己调用了sleep,yield,wait,join,park,synchronized,lock等方法
当上下文切换时,需要由OS保存当前线程的状态,并恢复另一个线程的状态
Java中对应的概念是程序计数器,作用是记住下一条jvm指令的地址,是线程私有的
常用方法
start:启动一个新线程,在新的线程中运行run方法中的代码
start方法只是让线程进入就绪,里面代码不一定立刻运行
每个线程对象只能调用一次start方法,否则会报IllegalThreadStateException
t1.interrupt()
// 打断t1线程
// 如果t1线程在sleep,wait会导致t1线程抛出InterruptedException,并清除打断标记
// 如果t1线程在运行,只是会设置打断标记
sleep:进入阻塞态,睡眠结束后的线程未必会立即得到执行,变为就绪态
Thread.yield():让线程让出cpu的使用权,进入就绪状态,使cpu调度其他就绪状态的线程
t1.join();主线程陷入阻塞,等待t1线程运行结束
FutureTask<Integer> fu = new FutureTask<>(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("p");
}
return 100;
});
Thread t1 = new Thread(fu);
Thread t2 = new Thread(() -> {
try {
long l = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
t1.join();
long r = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
System.out.println("==========等待时间==========" + (r - l));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t2.interrupt();// t2线程不再等待t1线程,且抛出异常InterruptedException
进程状态
就绪态:一个进程获得了除CPU之外的所有资源
阻塞态:一个进程正在等待某一事件而暂停运行
线程状态
A thread can be in only one state at a given point in time.
These states are virtual machine states which do not reflect any operating system thread states.
public enum State {
NEW,// Thread state for a thread which has not yet started.
// 就绪,运行,操作系统层面的阻塞状态
// Thread state for a runnable thread. A thread in the runnable state is executing in the
// Java virtual machine but it may be waiting for other resources from the operating system such as processor.
RUNNABLE,
// A thread in the blocked state is waiting for a monitor lock.
// to enter a synchronized block/method or reenter a synchronized block/method after calling {Object.wait}.
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the following methods:
* {Object.wait} with no timeout
* {Thread.join} with no timeout
* {LockSupport.park}
*
* A thread in the waiting state is waiting for another thread to perform a particular action.
*
* For example, a thread that has called {Object.wait()}
* on an object is waiting for another thread to call
* {Object.notify()} or {Object.notifyAll()} on
* that object. A thread that has called {Thread.join()}
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
*Thread.sleep,Object.wait,Thread.join,LockSupport.parkNanos,LockSupport.parkUntil
*/
TIMED_WAITING,
// Thread state for a terminated thread.The thread has completed execution.
TERMINATED;
}
默认情况下,Java进程需要等待所有线程都运行结束,才会结束
如果有一个守护线程,则只要其他非守护线程运行结束,整个程序就会结束
异步非阻塞模式