JUC 编程

什么是 JUC

JUC 编程

指的是java.util.concurrent工具包

业务:普通的线程代码 Thread
Runnable 没有返回值、效率相比于 Callable相对较低

线程和进程

线程、进程

  • 进程:一个程序,例如QQ.exe,程序的集合;
    一个进程往往可以包含多个线程,至少包含一个
    Java默认集合线程?2个 main、GC
  • 线程:开了一个进程Typora,写字,自动保存(线程负责)
    对java而言:Thread、Runnable、Callable

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();

并发、并行

并发编程:并发、并行

  • 并发(多个线程操作同一个资源)
    cpu一核,模拟出来多条线程,快速交替
  • 并行,CPU多核,多个线程可以同时执行;线程池
    public class Test1 {
      public static void main(String[] args) {
          //获取cpu的核数
          //CPU密集型,IO密集型
         System.out.println(Runtime.getRuntime().availableProcessors());
      }
    }
    并发编程的本质:充分利用CPU的资源

线程状态

Thread.State

//新生
NEW,

//运行
RUNNABLE,

//阻塞
BLOCKED,

//等待,死死的等
WAITING,

//超时等待
TIMED_WAITING,

//终止
TERMINATED;

wait/sleep

1、来自不同的类
wait => Object
sleep => Thread

2、关于锁的释放
wait 会释放锁,sleep睡着了,不会释放

3、使用的范围是不同的
wait必须在同步代码块中
sleep可以在任何地方睡

4、是否需要捕获异常
wait 不需要捕获异常
sleep 必须捕获异常
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!