码迷,mamicode.com
首页 > 编程语言 > 详细

Java 线程由浅入深 持续学习

时间:2019-05-15 23:59:45      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:gets   center   lru   独立   specified   返回   amp   ++   runnable   

线程状态

在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运行完毕后,如果后台线程还没有执行完毕,那么也是不会再执行了

Java 线程由浅入深 持续学习

标签:gets   center   lru   独立   specified   返回   amp   ++   runnable   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!