线程的创建方式
1.继承Thread类,重写run方法,示例如下:
 1 class PrimeThread extends Thread {
2 long minPrime;
3 PrimeThread(long minPrime) {
4 this.minPrime = minPrime;
5 }
6
7 public void run() {
8 // compute primes larger than minPrime
9 . . .
10 }
11 }
12 PrimeThread p = new PrimeThread(143);
13 p.start();
2.实现Runnable接口,(代理模式)实现run方法,将该对象作为构造参数构造一个Thread类实例,示例如下:
 1 class PrimeRun implements Runnable {
2 long minPrime;
3 PrimeRun(long minPrime) {
4 this.minPrime = minPrime;
5 }
6
7 public void run() {
8 // compute primes larger than minPrime
9 . . .
10 }
11 }
12 PrimeRun p = new PrimeRun(143);
13 new Thread(p).start();
线程Thread类及其start()方法和run()方法
1.Java线程的状态
  1. 初始(NEW):新创建了一个线程对象,但还没有调用start()方法。
  2. 运行(RUNNABLE):Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为“运行”。
线程对象创建后,其他线程(比如main线程)调用了该对象的start()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获取CPU的使用权,此时处于就绪状态(ready)。就绪状态的线程在获得CPU时间片后变为运行中状态(running)。
  3. 阻塞(BLOCKED):表示线程阻塞于锁。
  4. 等待(WAITING):进入该状态的线程需要等待其他线程做出一些特定动作(通知或中断)。
  5. 超时等待(TIMED_WAITING):该状态不同于WAITING,它可以在指定的时间后自行返回。
  6. 终止(TERMINATED):表示该线程已经执行完毕。
  threadStatus源码:
private volatile int threadStatus = 0;

public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
public static State toThreadState(int var0) {
if ((var0 & 4) != 0) {
return State.RUNNABLE;
} else if ((var0 & 1024) != 0) {
return State.BLOCKED;
} else if ((var0 & 16) != 0) {
return State.WAITING;
} else if ((var0 & 32) != 0) {
return State.TIMED_WAITING;
} else if ((var0 & 2) != 0) {
return State.TERMINATED;
} else {
return (var0 & 1) == 0 ? State.NEW : State.RUNNABLE;
}
}
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW, /**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE, /**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED, /**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING, /**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING, /**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
2.start()方法
  start方法的作用就是将线程由NEW状态,变为RUNABLE状态。当线程创建成功时,线程处于NEW(新建)状态,如果你不调用start( )方法,那么线程永远处于NEW状态。调用start( )后,才会变为RUNABLE状态,线程才可以运行。
调用start()方法后,线程是不是马上执行?
线程不是马上执行的;准确来说,调用start( )方法后,线程的状态是“READY(就绪)”状态,而不是“RUNNING(运行中)”状态。线程要等待CPU调度,不同的JVM有不同的调度算法,线程何时被调度是未知的。因此,start()方法的被调用顺序不能决定线程的执行顺序。
注意
  由于在线程的生命周期中,线程的状态由NEW ----> RUNABLE只会发生一次,因此,一个线程只能调用start()方法一次,多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。
strat()方法源码:
 1 public synchronized void start() {
2 // 如果线程不是"就绪状态",则抛出异常!
3 if (threadStatus != 0)
4 throw new IllegalThreadStateException();
5 // 将线程添加到ThreadGroup中
6 group.add(this);
7 boolean started = false;
8 try {
9 // 通过start0()启动线程,新线程会调用run()方法
10 start0();
11 // 设置started标记=true
12 started = true;
13 } finally {
14 try {
15 if (!started) {
16 group.threadStartFailed(this);
17 }
18 } catch (Throwable ignore) {
19 }
20 }
21 }
3.run()方法
  run()方法这里只是一个普通的方法,当线程调用了start( )方法后,一旦线程被CPU调度,处于运行状态,那么线程才会去调用这个run()方法。当然,thread示例也可以主动调用run()方法,不一定要start()发起。
run()方法源码:
1 public void run() {
2 if (target != null) {
3 target.run();
4 }
5 }
4.Thread对象
  Thread类的对象其实也是一个java对象,只不过每一个Thread类的对象对应着一个线程(映射)。Thread类的对象就是提供给用户用于操作线程、获取线程的信息。真正的底层线程用户是看不到的了。
因此,当一个线程结束了,死掉了,对应的Thread的对象仍能调用,除了start( )方法外的所有方法(死亡的线程不能再次启动),如run( )、getName( )、getPriority()等等。
 1 //简单起见,使用匿名内部类的方法来创建线程
2 Thread thread = new Thread(){
3 @Override
4 public void run() {
5 System.out.println("Thread对象的run方法被执行了");
6 }
7 };
8 //线程启动
9 thread.start();
10
11 //用循环去监听线程thread是否还活着,只有当线程thread已经结束了,才跳出循环
12 while(thread.isAlive()){}
13 //线程thread结束了,但仍能调用thread对象的大部分方法
14 System.out.println("线程"+thread.getName()+"的状态:"+thread.getState()+"---优先级:"+thread.getPriority());
15 //调用run方法
16 thread.run();
17 //当线程结束时,start方法不能调用,下面的方法将会抛出异常
18 thread.start();

多线程-2.线程创建方式和Thread类的更多相关文章

  1. 【多线程】线程创建方式三:实现callable接口

    线程创建方式三:实现callable接口 代码示例: import org.apache.commons.io.FileUtils; import java.io.File; import java. ...

  2. python 多线程编程之threading模块(Thread类)创建线程的三种方法

    摘录 python核心编程 上节介绍的thread模块,是不支持守护线程的.当主线程退出的时候,所有的子线程都将终止,不管他们是否仍在工作. 本节开始,我们开始介绍python的另外多线程模块thre ...

  3. JAVA与多线程开发(线程基础、继承Thread类来定义自己的线程、实现Runnable接口来解决单继承局限性、控制多线程程并发)

    实现线程并发有两种方式:1)继承Thread类:2)实现Runnable接口. 线程基础 1)程序.进程.线程:并行.并发. 2)线程生命周期:创建状态(new一个线程对象).就绪状态(调用该对象的s ...

  4. Java多线程学习(二)---线程创建方式

    线程创建方式 摘要: 1. 通过继承Thread类来创建并启动多线程的方式 2. 通过实现Runnable接口来创建并启动线程的方式 3. 通过实现Callable接口来创建并启动线程的方式 4. 总 ...

  5. Java实现线程的两种方式?Thread类实现了Runnable接口吗?

    Thread类实现了Runnable接口吗? 我们看看源码中对与Thread类的部分声明 public class Thread implements Runnable { /* Make sure ...

  6. Java基础加强之多线程篇(线程创建与终止、互斥、通信、本地变量)

    线程创建与终止 线程创建 Thread类与Runnable接口的关系 public interface Runnable { public abstract void run(); } public ...

  7. Java基础之多线程篇(线程创建与终止、互斥、通信、本地变量)

    线程创建与终止 线程创建 Thread类与Runnable接口的关系 public interface Runnable { public abstract void run(); } public ...

  8. Java:多线程概述与创建方式

    目录 Java:多线程概述与创建方式 进程和线程 并发与并行 多线程的优势 线程的创建和启动 继承Thread类 start()和run() 实现Runnable接口 实现Callable接口 创建方 ...

  9. java多线程(一)-五种线程创建方式

    简单使用示例 Java 提供了三种创建线程的方法: 通过实现 Runnable 接口: 通过继承 Thread 类本身: 通过 Callable 和 Future 创建线程. 还有 定时器 线程池 下 ...

随机推荐

  1. AES加密--适用于RC2、RC4和Blowfish

    package test; import java.security.GeneralSecurityException; import java.security.Key; import javax. ...

  2. 绿色物流-智慧仓储监控管理 3D 可视化系统

    前言 随着电子商务产业的迅速发展,快递爆仓已成为了困扰仓储物流的一大难题.大量的碎片化订单,传统仓储管理和运作方式已无法满足,加速仓储物流管理的智能化.自动化升级创新,延伸而出的智慧物流概念成为物流行 ...

  3. 15款NOSQL数据库

    1.MongoDB 介绍 MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.主要解决的是海量数据的访问效率问题,为WEB应用提供可扩展的高性能数据存储解决方案.当数据量达到50GB以上 ...

  4. 攻防世界 reverse Newbie_calculations

    Newbie_calculations Hack-you-2014 题目名百度翻译成新手计算,那我猜应该是个实现计算器的题目.... IDA打开程序,发现一长串的函数反复调用,而且程序没有输入,只有输 ...

  5. 1、Spring教程之Spring概述

    1.Spring概述 简介 Spring : 春天 --->给软件行业带来了春天 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架. 2004年3月24 ...

  6. 前端常见的请求数据汇总(GET POST)

    前端在请求接口的时候要和后端人员配合好,根据后端提供的接口文档来进行开发,一般请求类型有这几种 1.GET请求 GET请求一般会将数据放到URL后 GET请求对所发信息量的限制是2000个字符 GET ...

  7. 最短路径(Dijskra算法)

    声明:图片及内容基于:https://www.bilibili.com/video/BV16C4y1H7Zc?from=articleDetail 最短路径 Dijkstra算法 原理 数据结构 核心 ...

  8. 「HTML+CSS」--自定义加载动画【010】

    前言 Hello!小伙伴! 首先非常感谢您阅读海轰的文章,倘若文中有错误的地方,欢迎您指出- 哈哈 自我介绍一下 昵称:海轰 标签:程序猿一只|C++选手|学生 简介:因C语言结识编程,随后转入计算机 ...

  9. 201871030139-于泽浩 实验二 个人项目D{0-1} KP

    201871030139-于泽浩 实验二 个人项目D{0-1} KP 项目 内容 课程班级博客连接 2018级卓越班 这个作业要求连接 软件工程个人项目 我的课程学习目标 (1)掌握软件项目个人开发流 ...

  10. 四单元总结&OO总结

    目录 本单元架构总结 第一次作业 第二次作业 第三次作业 架构设计总结 第一单元 第二单元 第三单元 对测试演进 课程收获 改进建议 线上学习体验 本单元架构总结 第一次作业 第一次作业按照UML正常 ...