Java 线程由浅入深 持续学习

线程状态

在Thread.State 中关于线程状态的解释

  • NEW

    Thread state for a thread which has not yet started.

  • RUNNABLE

    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.

  • BLOCKED

    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 Object.wait().

  • WAITING

    Thread state for a waiting thread.
    A thread is in the waiting state due to calling one of the following methods:

    • Object.wait()with no timeout
    • Thread.join() with no timeout
    • LockSupport.park()

    A thread in the waiting state is waiting for another thread to perform a particular action.
    For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.

  • TIMED_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:

    • Thread.sleep
    • Object.wait(long)with timeout
    • Thread.join(long)with timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil
  • TERMINATED

    Thread state for a terminated thread.
    The thread has completed execution.

    线程优先级

    每个线程都有一个优先级以便操作系统确定线程的调度顺序
    根据Thrad类初始化方法,每个线程在初始化时都会从当前线程中取出一些属性来设置给自身,其中包括线程的priority。在Thread中同时定义有NORM_PRIORITY默认优先级5,以及MIN_PRIORITY最小1,MAX_PRIORITY最大10
    较高优先级的线程会在低优先级的线程之前分配处理器资源。但是,线程优先级不能保证线程执行的顺序

    线程创建

    三种创建线程的方法:

  • 实现Runnable接口
  • 继承Thread类
  • 通过 Callable 和 Future 创建线程

    实现Runnable接口创建线程

    创建类实现Runnable接口,实现run 方法

public class MyThreadImplRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + Thread.currentThread().getState());
        for (int i = 0 ; i < 100 ;i++) {
            System.out.println(Thread.currentThread().getName() + "-" + i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "exit");
    }
}

创建启动线程

public static void main(String[] args) {
    Thread t1 = new Thread(new MyThreadImplRunnable(),"thread1");
    System.out.println("thread1" + t1.getState());
    t1.start();
    Thread t2 = new Thread(new MyThreadImplRunnable(),"thread2");
    System.out.println("thread2" + t2.getState());
    t2.start();
}

执行结果

thread1NEW
thread2NEW
thread1RUNNABLE
thread1-0
thread2RUNNABLE
thread2-0
thread1-1
thread2-1
thread2-2
thread1-2
thread1-3
thread2-3
thread1-4
thread2-4
thread1exit
thread2exit

继承Thread创建线程

创建类来继承Thread,实现run方法

public class MyThreadExtThread extends Thread {
    public MyThreadExtThread(String threadName) {
        super(threadName);
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + Thread.currentThread().getState());
        for (int i = 0 ; i < 5 ;i++) {
            System.out.println(Thread.currentThread().getName() + "-" + i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "exit");
    }
}

启动线程

public static void main(String[] args) {
    Thread t1 = new MyThreadExtThread("thread1");
    System.out.println("thread1" + t1.getState());
    t1.start();
    Thread t2 = new MyThreadExtThread("thread2");
    System.out.println("thread2" + t2.getState());
    t2.start();
}

执行结果

thread1NEW
thread2NEW
thread1RUNNABLE
thread1-0
thread2RUNNABLE
thread2-0
thread1-1
thread2-1
thread2-2
thread1-2
thread1-3
thread2-3
thread1-4
thread2-4
thread1exit
thread2exit

Thread 类的方法

序号 方法描述
1 public void start()
使该线程开始执行;
Java 虚拟机调用该线程的 run 方法。
2 public void run()
如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;
否则,该方法不执行任何操作并返回。
3 public final void setName(String name)
改变线程名称,使之与参数 name 相同。
4 public final void setPriority(int priority)
更改线程的优先级。
5 public final void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。
6 public final void join(long millisec)
等待该线程终止的时间最长为 millis 毫秒。
7 public void interrupt()
中断线程。
8 public final boolean isAlive()
测试线程是否处于活动状态。

Thread类的静态方法

序号 方法描述
1 public static void yield()
暂停当前正在执行的线程对象,并执行其他线程。
2 public static void sleep(long millisec)
在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
3 public static boolean holdsLock(Object x)
当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true。
4 public static Thread currentThread()
返回对当前正在执行的线程对象的引用。
5 public static void dumpStack()
将当前线程的堆栈跟踪打印至标准错误流。

在执行线程测试的时候发现一个有趣的现象,使用junit进行测试时,有时能够执行完达到预期的效果,有时并不能。
经过百度后发现原来Junit只管自己的运行,就是说当Junit执行完毕后,就会关闭程序,不会关心是否还有自己启动的后台线程在运行。当Junit运行完毕后,如果后台线程还没有执行完毕,那么也是不会再执行了

原文地址:https://www.cnblogs.com/herberts/p/10872987.html

时间: 2024-08-03 18:54:15

Java 线程由浅入深 持续学习的相关文章

java线程池的学习

package advancedJava;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit; * java 线程池学习 * @author: cuiH * Date: 13-12-7public class ThreadPoolTest { * 线程池的概念 * jdk5提出了ThreadPool的概念 * 之

【Java线程池快速学习教程】

1. Java线程池 线程池:顾名思义,用一个池子装载多个线程,使用池子去管理多个线程. 问题来源:应用大量通过new Thread()方法创建执行时间短的线程,较大的消耗系统资源并且系统的响应速度变慢.[在一个什么程度上能够判断启用线程池对系统的资源消耗比启动定量的new Thread()资源消耗低?这个怎么测试?][用户体验卡顿?慢?观察CPU百分比?] 解决办法:使用线程池管理短时间执行完毕的大量线程,通过重用已存在的线程,降低线程创建和销毁造成的消耗,提高系统响应速度. 2. Java线

java线程的中断学习

<span style="font-size:18px;">package thread.java.test; /** * 在这里练习的是线程的中断 * Thread.interrupt()来设置中断状态是true,当一个线程运行时,另一个线程可以调用另一个 * 线程的interrupt()方法来中断他 * Thread.isInterrupt()来获取线程的中断状态 * Thread.interrupted()这是一个静态的方法,用来获取中断状态,并清除中断状态, * 其

Java线程安全synchronize学习

Java中,synchronized关键字有2种用法: 作为关键字修饰方法 修饰一个代码块 [TOC] 线程争用 为了探究synchronized的具体用法,可以用一个简单的程序来说明: package fc.learn.java.synchronize; import java.util.Random; public class LearningSynchronized { public enum SyncTypeTag { OBJ_METHOD, CLASS_METHOD, KEYWARD_

Java线程池详解(二)

一.前言 在总结了线程池的一些原理及实现细节之后,产出了一篇文章:Java线程池详解(一),后面的(一)是在本文出现之后加上的,而本文就成了(二).因为在写完第一篇关于java线程池的文章之后,越发觉得还有太多内容需要补充,每次都是修修补补,总觉得还缺点什么.在第一篇中,我着重描述了java线程池的原理以及它的实现,主要的点在于它是如何工作的.而本文的内容将更为上层,重点在于如何应用java线程池,算是对第一篇文章的一点补充,这样对于java线程池的学习和总结稍微完整一些. 使用过java线程池

Java线程学习经典例子-读写者演示

Java线程学习最经典的例子-读写者,主要用到Thread相关知识如下: -         线程的start与run -         线程的休眠(sleep) -         数据对象加锁(synchronized) -         数据对象的等待与释放(wait and notify) 程序实现: -ObjectData数据类对象,通过synchronized关键字实现加锁,在线程读写者中使用. -ConsumerThread消费者线程,读取数据对象中count值之后,通知生产者

Java 线程池学习

Reference: <创建Java线程池>[1],<Java线程:新特征-线程池>[2], <Java线程池学习>[3],<线程池ThreadPoolExecutor使用简介>[4],<Java5中的线程池实例讲解>[5],<ThreadPoolExecutor使用和思考>[6] [1]中博主自己通过ThreadGroup实现一个线程池(挺方便理解的),使用的是jdk1.4版本,Jdk1.5版本以上提供了现成的线程池. [2]中介绍

黑马程序与----java线程学习

线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元.一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成.另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源.一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行.由于线程之间的相互制约,致使线程在运行中呈现出间断性.线程也有就绪.阻塞和运

Java线程学习笔记(二) 线程的异常捕捉

线程异常的捕捉: 正常的情况下,我们在main()方法里是捕捉不到线程的异常的,例如以下代码: public class ExceptionThread implements Runnable{ @Override public void run() { throw new NullPointerException(); } public static void main(String[] args) { ExecutorService executorService = Executors.n