JUC详解 消费者生产者

1.1.1 JUC并发升级

业务:普通的线程代码 Thread

Runnable 没有返回值 效率相比callable低

JUC详解 消费者生产者

1.1.2线程和进程

一句话说不出来的技术 就是不扎实

java 默认有几个线程 2个 main 和GC

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 */
        }
    }
}
//底层调用native方法 使用c++编写
private native void start0();

底层调用native方法 使用c++编写

1.1.3 并发和并行

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

  • 一核 ,交替运行 ,造成假象

并行 优化使用线程池

  • 多核心cpu ,多个线程可以同时执行

查看本机有几核

JUC详解 消费者生产者

package com.cjg.juc;

public class demo01 {
    public static void main(String[] args) {
       // new Thread().start();
        //获取cpu的核数
        //cpu 密集型 和io密集型
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

并发的本质:充分利用cpu的资源

线程有几个状态

新生
    NEW,

运行
    RUNNABLE,

 阻塞
    BLOCKED,

  等待 死等
    WAITING,

   超时等待
    TIMED_WAITING,

    终止
    TERMINATED;
}

wait/sleep 区别

wait ==>object

sleep==>Thread

上一篇:一起学Go吧! Go语言面向对象篇(不是面向女友!)


下一篇:2-08_抽象类特点