什么是JUC

什么是JUC与线程和进程

一、什么是JUC

面试高频问 java util concurrent
在这里插入图片描述
java.util 工具包 包、分类

业务:普通的线程代码 Thread

Runnable: 没有返回值,效率相比Callable相对较低
在这里插入图片描述

二、线程和进程

线程和进程

线程、进程

进程是操作系统中的应用程序,是资源分配的基本单位。线程的用来执行具体的任务和功能,是cpu调度和分派的基本单位

进程:一个程序 qq.exe Music.exe 程序的集合;

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

​ Java默认有两个线程。main、GC

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

对于Java而言:Thread、Runnable、Callable

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

扫描二维码关注公众号,回复: 13142998 查看本文章
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();

并发、并行

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

  • CPU一核:模拟出来多条线程,天下武功,唯快不破,快速交替执行线程模拟

并行(多个人一起行走)

  • CPU多核:多个线程同时执行 最高性能 使用线程池操作
package com.can.demo01;

public class Test1 {
    
    
    public static void main(String[] args) {
    
    
        //获取cpu的核数
        //CPU密集型,IO密集型
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

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

线程有几个状态 6个

public enum State {
    
    
    // 新生
    NEW,

    // 运行
    RUNNABLE,

    // 阻塞
    BLOCKED,

    // 等待,死等
    WAITING,

    // 超时等待,超时不等
    TIMED_WAITING,

    // 终止
    TERMINATED;
}

wait/sleep区别

1、来自不同的类

wait->Object

sleep->Thread

2、关于锁的释放

wait 会释放锁

sleep 不释放锁

3、使用的范围是不同的

wait 只能在同步代码块中使用

// 同步代码块
synchronized(obj){
    
    
    //需要被同步的代码块
}

sleep 可以在任何地方睡

4、是否需要捕获异常

wait 不需要捕获异常 线程中断都会抛出异常

sleep 必须要捕获异常

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43803285/article/details/115373967
JUC