Skip to content
DAILY QUOTE

“ ”

进程:一个程序,QQ.exe,music.exe 本质是程序的集合, (JVM就是一个进程,管理着无数的线程)

一个进程往往可以包含多个线程,至少包含一个

Java默认有几个线程? 2个:main和GC

线程:开了一个进程Typora,写字,自动保存(线程负责的)

开启线程,对于Java而言:Thread、Runnable、Callable

Java 真的可以开启线程吗? 开不了

java
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread 
     * or "system" group threads created/set up by the VM. Any new 
     * functionality added to this method in the future may have to 
     * also be added to the VM.A zero status value corresponds to 
     * state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    /* 
     * Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. 
     */
    group.add(this);
    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}
// 本地方法,底层操作的是C++ ,Java 无法直接操作硬件
private native void start0();
//native:具体实现不在java代码中,直接去调用c/c++写的动态链接库

并行、并发

并发(多线程操作同一个资源)

  • 一核CPU,模拟出来多条线程,快速交替。

并行(多个人一起行走)

  • 多核CPU ,多个线程可以同时执行; eg: 线程池
java
public class Test1 {
    public static void main(String[] args) {
      // 获取cpu的核数 
      // CPU 密集型,IO密集型 
        System.out.println(Runtime.getRuntime().availableProcessors());
      // 如果电脑是8核,则结果输出8
     } 
}

并发编程的本质:充分利用CPU的资源

线程有几个状态(6个)

java
public enum State {
    // 新生
    NEW,
	// 运行
    RUNNABLE,
	// 堵塞
    BLOCKED,
	// 等待,死死地等
    WAITING,
	// 超时等待
    TIMED_WAITING,
	// 终止
    TERMINATED;
}

wait/sleep区别

  1. 二者来自不同的类
  • wait=>Object
  • sleep=>Thread
  1. 关于锁的释放
  • wait 会释放锁
  • sleep 睡觉了,抱着锁睡觉,不会释放!
  1. 使用的范围是不同的
  • wait必须在同步代码块中使用
  • sleep可以在任何地方