2021-10-08——线程和进程

进程一个程序的集合,一个程序通常包含多个线程(最少一个)
JAVA默认有几个线程? main ,GC
JAVA开启线程有
Thread,Runnable,Callable
Java真的可以开启线程嘛?不可以直接开启

这是一个C++底层,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();

Java是没有权限去开启线程、操作硬件的,这是一个native的一个本地方法,它调用的底层的C++代码。
并发、并行
并发: 多线程操作同一个资源。
CPU 只有一核,模拟出来多条线程,天下武功,唯快不破。那么我们就可以使用CPU快速交替,来模拟多线程。
并行: 多个人一起行走

获取CPU核数
package com.Thread;
public class CPU {
        public static void main(String[] args) {
            //获取cpu的核数
            System.out.println(Runtime.getRuntime().availableProcessors());
    }
}
线程的状态
public enum State {
 		//创建
        NEW,
		//运行
        RUNNABLE,
		//阻塞
        BLOCKED,
      	//等待
        WAITING,
		//超时等待
        TIMED_WAITING,
        //终止
        TERMINATED;
    }
wait/sleep的区别

1、来自不同的类

wait => Object
sleep => Thread

1,一般情况企业中使用休眠是:

TimeUnit.DAYS.sleep(1); //休眠1天
TimeUnit.SECONDS.sleep(1); //休眠1s

2、关于锁的释放

wait 会释放锁;
sleep睡觉了,不会释放锁;

3、使用的范围是不同的

wait 必须在同步代码块中;
sleep 可以在任何地方睡;

4、是否需要捕获异常

wait是不需要捕获异常;
sleep必须要捕获异常;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值