[Java多线程]继承Thread类/实现Runnable接口

目录

1进程与线程:

1.1进程:

1.2线程:

1.3两者关系:

2多线程的实现:

2.1继承Thread类(单继承局限)

总结:

2.2Runnable接口实现多线程

2.3继承Thread类与实现Runnable接口的关系:


1进程与线程:

1.1进程:

一个操作系统中一个程序的执行周期

1.2线程:

一个进程同时执行多个任务。通常来讲,每个任务就可以成称为一个线程

1.3两者关系:

1.线程更加的“轻量级”,创造和撤销一个线程比启动撤销一个进程的开销小的多

一个进程中所有线程共享此进程的所有资源

2.没有进程就没有线程,进程一旦终止,线程也将不复存在

3.进程是操作系统资源调度的基本单位,进程可以共享资源

线程需要依靠进程提供的资源,无法独立申请操作系统资源,是os任务执行的基本单位。

高并发:

指的是同一时刻访问的线程量特别高

2多线程的实现:

2.1继承Thread类(单继承局限)

java.lang.Thread是线程操作的核心类.新建一个线程最简单的方法就是继承Thread类.而后覆写run()方法(相当于主线程的main()方法)

//无论使用哪种方式实现线程,线程的启动一定调用Thread类提供的start()方法

//start源码:
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 */
     }
   }
 }
  private native void start0();

由源码可知:

1线程的start()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值