Thread类的api笔记

并发与并行的概念

  1. 并行:当系统有一个以上CPU时,当一个CPU执行一个进程时,另一个CPU可以执行另一个进程,两个进程互不抢占CPU资源,可以同时进行,这种方式我们称之为并行。
  2. 并发:在操作系统中,是指一个时间段中有几个程序都处于已启动运行到运行完毕之间,且这几个程序都是在同一个处理机上运行。
  3. 并行和并发的区别.
    3.1并行只可能发生在多个CPU的情况下,而并发可能发生在一个CPU运行的情况下。
    3.2并行是没有对资源的抢占,不存在竞争和等待的,而并发执行的线程需要抢占资源、可能会产生竞争和等待的情况。
    3.3并行执行的线程之间不存在切换,而并发执行的线程之间存在切换的情况。

线程的API介绍

Java中的线程:在Java应用程序中,我们的程序的入口main方法,在运行时就是一个线程,这个线程是被JVM去创建并调用的,线程名字是main

通过源码可知,调用线程的start方法最后是去调用一个native的start0方法,但是没有任何地方能够发现和run方法有联系的,是因为创建线程之后,是通过JVM(C++代码)回调我们的run方法去执行的。

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 */
            }
        }
    }

Thread的无参构造器:调用init方法,给线程取一个默认的名字后缀是自增的int值转为String的对象;
在这里插入图片描述
带有一个Runnable的构造器、带有一个线程组的构造器、带有一个字符串的构造器(字符串为线程名称)、带有一个线程组和一个Runnable的构造器、带有一个线程组和线程名称的构造器、带有一个Runable和线程名称的构造器、带有一个线程组和Runnable和线程名称的构造器、带有一个线程组和Runable和线程名称和线程栈大小的构造器。
在这里插入图片描述
传入stackSize代表着该线程占用的栈的大小,如果没有指定这个参数,默认是0代表忽略该参数,该参数会被JVM去使用,注意:该参数高度依赖于平台(操作系统),所以有些平台是设置了也无效的。一般我们也不会在线程中去设定,都是通过JVM参数:Xss6M,去指定其大小。
Thread的id和优先级:id一般用于定位死锁或者定位OOM时去使用,优先级是指尽可能的让CPU去优先执行优先级更高的线程(但是不能绝对的决定CPU的调度)
Thread的线程组如果在创建线程时没有指定线程组,那么会将被创建的线程的线程组设置为创建该线程的线程的线程组:

private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name.toCharArray();

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

守护线程

  1. 设置守护线程后,所有用户线程死亡时,
  2. 守护线程才会跟着一起死亡。
public class ThreadDaemonTest01 {

	public static void main(String[] args) throws InterruptedException {

		Thread t=new Thread("Jack"){
			
			@Override
			public void run() {
				try {
					String threadName = Thread.currentThread().getName();
					while(true){
						Thread.sleep(1_000);
						System.out.println(threadName+
								":你到底跳不跳?要跳就跳啊!你敢跳下去我就敢和你一起跳!");
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		
		t.setDaemon(true);
		t.start();
		//主线程休息100毫秒让Jack可以启动。
		Thread.sleep(100);
		for(int i=0;i<5;i++){
				System.out.println("Rose:我还有"+(5-i)+"秒就要跳下去了!");
				Thread.sleep(1_000);
				if(i==4){
					System.out.println("Rose::我跳了……啊!!!!");
				}
		}
		System.out.println("声效:噗通!!!");
	}

}

运行结果
在这里插入图片描述
注意
设置守护线程必须在主线程start()之前,如果在主线程调用start()方法之后,那么会抛出java.lang.IllegalThreadStateException。

线程的join()方法

让当前线程等待调用线程执行完后再执行

public class ThreadJoinTest01 {

	public static void main(String[] args) throws InterruptedException {
		Thread t=new Thread("线程1"){
			@Override
			public void run() {
				try {
					String threadName = Thread.currentThread().getName();
					for(int i=0;i<5;i++){
						Thread.sleep(1_000);
						System.out.println(threadName+":我是复读机,我每秒钟复读一次,共复读5次……");
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		
		t.start();
		//让当前线程(main线程)等到线程1执行完毕后再执行
		t.join();
		
		//休息一下让线程1启动
		Thread.sleep(100);
		for(int i=0;i<3;i++){
			Thread.sleep(1_000);
			System.out.println("main:我也是复读机,我每秒钟复读一次,共复读3次……");
		}
		
		
	}

}

结果显示
在这里插入图片描述

interrupt方法的使用

  • 对线程中断状态的判断
  • 中断状态:实际上是在线程执行过程中打上一个标记 或者抛出一个异常,然后线程会继续将剩下的逻辑执行完毕,也就是说在线程被中断后,线程的生命周期并没有结束。
public class ThreadInterruptTest01 {

	public static void main(String[] args) throws InterruptedException {
		

		//创建一个线程执行死循环
		Thread t = new Thread("线程1"){
			
			@Override
			public void run() {
				//执行了一个耗时很长的逻辑(在执行的逻辑中没有任何的阻塞情况)
				while(true){
					//在线程1中去判断当前线程是否被中断了
					if(this.isInterrupted()){
						System.out.println("线程1内部判断被中断了吗?"+this.isInterrupted());
						break;
					}
				}
			}
			
		};
		t.start();
		
		//休眠一下,让t这个线程先启动起来到达运行的状态
		Thread.sleep(100);
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName+":线程1中断了么?"+t.isInterrupted());
		//中断t这个线程
		t.interrupt();
		System.out.println(threadName+":线程1中断了么?"+t.isInterrupted());
		
	}

}

执行结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值