java系列之多线程(线程创建和常见线程方法)

178 阅读2分钟

一、创建一个线程

1.继承Thread类

继承Thread类之后,重写run方法即可

 public class MyThread extends Thread {
    @Override
    public void run(){
         System.out.println("MyThread====="+Thread.currentThread().getName());
    }
} 

2.实现Runnable接口

因为java只支持单继承,因而一般上实现Runnable接口相对而言可以达到边实现线程边继承的目的。

//这里首先先创建一个Runnable对象
public class MyRunnable implements Runnable {
    @Override
    public void run(){
        System.out.println("MyRunnable====="+Thread.currentThread().getName());
    }
}
//然后还需要通过Thread的构造方法,创建一个Thread对象才算创建了一个线程对象
public static void main(String[] args){
        MyRunnable myRunnable=new MyRunnable();
        Thread myRunnableThread=new Thread(myRunnable);
}
对于这两种方式创建的线程而言,运行方式是没有什么差别的。

3.启动线程

    public static void main(String[] args){
        MyThread myThread=new MyThread();
        //启动线程
        myThread.start();
        MyRunnable myRunnable=new MyRunnable();
        Thread myRunnableThread=new Thread(myRunnable);
        //启动线程
        myRunnableThread.start();
    }

这里需要稍微注意下:

1.如果要启动一个线程,必须调用这个线程的start()方法,不能直接调用对象的run方法:因为如果单纯的调用run方法,只是相当于调用普通类的一个方法,不会新开一个线程,而是在当前线程中调用对象的run方法。

2.多个线程的运行顺序不是取决于代码中线程的启动顺序,而是要看CPU的执行调度顺序。

二、线程的基本方法

1.currentThread

其实上面的创建线程例子已经涉及到这个方法。下面我们看一下Thread类中对于这个方法的描述

     /**
     * Returns a reference to the currently executing thread object.
     *
     * @return  the currently executing thread.
     */
    public static native Thread currentThread();

起作用不言而喻,获取到当前正在执行的线程对象。通过这个方法,我们能够获取到当前线程的一些属性信息。比如线程的优先级,线程名称、是否是守护线程等。

2.currentThread

     /**
     * Tests if this thread is alive. A thread is alive if it has
     * been started and has not yet died.
     *
     * @return  <code>true</code> if this thread is alive;
     *          <code>false</code> otherwise.
     */
    public final native boolean isAlive();

我们可以看出来这个是判断线程当前是否处于活动状态的,如果是则方法返回Ture,否则返回false。活动状态是指线程已经启动而且还没有终止。 下面我们举个例子看一下:

public class TestCreateThread {
  public static void main(String[] args){
      MyThread t1=new MyThread();
      //启动线程
      System.out.println("isAlive======="+t1.isAlive());
      t1.start();
      System.out.println("isAlive======="+t1.isAlive());
      try {
          TimeUnit.MILLISECONDS.sleep(1L);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      System.out.println("isAlive======="+t1.isAlive());
  }
  private static class MyThread extends Thread {
      @Override
      public void run(){
          System.out.println("isAlive======="+Thread.currentThread().isAlive());
      }
  }
}
执行结果:
isAlive=======false
isAlive=======true
isAlive=======true
isAlive=======false

从执行结果我们可以看到,当在t1.start()之前打印,这个时候线程还没启动,所以返回false;最后一个打印是在主方法停住1毫秒之后,这个时候t1线程已经执行完毕,所以打印出来是false。而中间的两次则都是处于活动状态。