美文网首页
Java - 线程 & 线程池

Java - 线程 & 线程池

作者: 齐晋 | 来源:发表于2019-03-01 20:17 被阅读0次

概述:创建线程有两种方法,一种是继承Thread类,另一种是实现Runnable接口。

创建线程

创建线程有两种方法:

  1. 继承Thread类
  2. 实现Runnable接口

继承Thread类

public class ExtendThead extends Thread{

    private int no;

    public ExtendThead(int no){
        this.no = no;
    }

    @Override
    public void run(){
        try {
            for(int i = 1; i <6; i++) {
                System.out.println("Child Thread: " + no + "-" + i);
                // 让线程休眠一会
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
        System.out.println("Exiting child thread.");
    }
}

//==============================
public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能启动新的线程。
        new ExtendThead(1).start();  
        new ExtendThead(2).start();
        new ExtendThead(3).start();
        new ExtendThead(4).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 让线程休眠一会
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

实现Runnable接口

public class RunnableThread implements Runnable{

    private int no;

    public RunnableThread(int no){
        this.no = no;
    }

    @Override
    public void run(){
        try {
            for(int i = 1; i <6; i++) {
                System.out.println("Runnable Thread: " + no + "-" + i);
                // 让线程休眠一会
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Runnable interrupted.");
        }
        System.out.println("Exiting Runnable thread.");
    }
}

//==============================
public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能启动新的线程。
        new Thread(new RunnableThread(1)).start();
        new Thread(new RunnableThread(2)).start();
        new Thread(new RunnableThread(3)).start();
        new Thread(new RunnableThread(4)).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 让线程休眠一会
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

注意:实现Runnable接口的类没有任何线程能力,只有将其显示地附着在一个线程上,才会有线程能力。即只能将Runnable类的实例通过参数传入Thread类实例来启动线程:new Thread(Runnable).start()

很多情况下,使用Runnable接口创建线程时,直接使用匿名类的方法创建,会更简单:

public static void main( String[] args ){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i = 1; i <6; i++) {
                        System.out.println("Runnable Thread: " + i);
                        // 让线程休眠一会
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    System.out.println("Runnable interrupted.");
                }
            }
        }).start();

    }

Thread 和Runnable的区别

  • Thread是个class,java中class只能单继承
  • Runnable是个Interface,扩展性比较好
  • Runnable定义的子类中没有start()方法,只有Thread类中才有。因此使用Runnable要通过Thread。new Thread(new Runnable)

线程的一些特征

返回值

如果希望任务完成时,返回一个结果,就不能使用Thread和Runnable。这时需要实现Callable接口,并必须使用ExecutorService.submit()方法来调用。

Callable定义如下。可以看到Callable接口只有一个call()方法,并且支持返回值。

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

ExecutorService的submit方法:

public interface ExecutorService extends Executor {
    <T> Future<T> submit(Callable<T> task);
}

返回值是一个Future对象。

public interface Future<V> {
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

可以通过调用Future对象的isDone()方法来查看任务是否已经完成。或者使用get()方法来获取返回结果。注意,get()会阻塞主线程,直至子线程任务完成。所以一般情况下,在直接调用get()方法之前,会首先使用isDone()或者带有超时的get()方法查看任务是否完成。

休眠

让线程休眠一段时间,方法是Thread.sleep(milliseconds)

线程优先级

使用getPriority()方法来获取线程优先级。
使用setPriority()方法来设定线程的优先级。

public class Thread implements Runnable {
    **
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;
}

可以看到,JDK定义了10个优先级。不过多数与操作系统映射的不好。比如Windows有7个优先级,其映射关系还不固定。所以,为了方便移植,最好只使用Thread中定义的三种优先级。

public class Test implements Runnable{
    public void run(){
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        //do something
    }
}

注意:

  1. 设置线程优先级通常在run()方法的开头设置。
  2. 极其不建议改变线程优先级。

Daemon线程

Daemon线程即后台线程。
与后台线程对应的是非后台线程。如主线程是非后台线程,启动的默认设置线程也是非后台线程。
非后台线程有个特点是:只要有任何一个非后台线程正在运行,程序就不会终止。
与之对应,后台线程特点是,当所有非后台线程结束时,程序会终止,此时会结束所有后台线程。任何一个非后台线程结束时,都会杀死该非后台线程启动的后台线程。

设置线程为后台线程的方法:new Thread().setDaemon(true)

如:

Thread test = new Thread(new Runnable(){
    public void run(){
        //do something
    }
});
test.setDaemon(true);
test.start();

可以通过isDaemon()方法判断一个线程是否是后台线程。

主线程等待子线程结束

使用join

public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能启动新的线程。
        Thread t1 = new Thread(new RunnableThread(1)).start();
        Thread t2 = new Thread(new RunnableThread(2)).start();
        Thread t3 = new Thread(new RunnableThread(3)).start();
        Thread t4 = new Thread(new RunnableThread(4)).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 让线程休眠一会
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t1.join();
        t2.join();
        t3.join();
        t4.join();
    }
}

线程池

请见 Java线程池

参考

相关文章

网友评论

      本文标题:Java - 线程 & 线程池

      本文链接:https://www.haomeiwen.com/subject/kapjuqtx.html