线程管理

1.1 线程的创建和运行

    在Java中,我们有2个方式创建线程:

    1、通过直接继承thread类,然后覆盖run()方法。

    2、构建一个实现Runnable接口的类, 然后创建一个thread类对象并传递Runnable对象作为构造参数

在下面的示例中,我们将使用两种方法来制作一个简单的程序,它能创建和运行10个线程。每一个线程能计算和输出1-10以内的乘法表。

    实现Runnable接口:

public class Calculator implements Runnable{

    private int number;

 

    public Calculator(int number) {

        this.number = number;

    }

 

    @Override

    public void run() {

        for(int i = 0; i < 10; i++) {

            System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);

        }

    }

}

 

public class Main {

    public static void main(String[] args) {

 

    for(int i = 0; i < 10; i++) {

    Calculator cal = new Calculator(i);

    Thread thread = new Thread(cal);

    thread.start();

    }

}

 

继承Thread类:

public class Calculator extends Thread{

    private int number;

 

    public Calculator(int number) {

    this.number = number;

    }

 

    @Override

    public void run() {

    for(int i = 0; i < 10; i++) {

         System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);

    }

}

 

public class Main {

    public static void main(String[] args) {

        for(int i = 0; i < 10; i++) {

            Thread thread = new Calculator(i);

            thread.start();

        }

    }

}

    每个Java程序最少有一个执行线程。当你运行程序的时候, JVM运行负责调用main()方法的执行线程。

    当调用Thread对象的start()方法时, 我们创建了另一个执行线程。在这些start()方法调出后,我们的程序就有了多个执行线程。

    当全部的线程执行结束时(更具体点,所有非守护线程结束时),Java程序就结束了。如果初始线程(执行main()方法的主线程)运行结束,其他的线程还是会继续执行直到执行完成。但是如果某个线程调用System.exit()指示终结程序,那么全部的线程都会结束执行。

    创建一个Thread类的对象不会创建新的执行线程。同样,调用实现Runnable接口的 run()方法也不会创建一个新的执行线程。只有调用start()方法才能创建一个新的执行线程。

1.2 线程信息的获取和设置

    Thread有一些保存信息的属性:

        ID:保存了线程的唯一标识符

        Name:保存了线程的名称

        Priority:保存了线程对象的优先级。优先级从0-10,1最低,10最高

        Status:保存的线程的状态。在java中,一共有六种状态:new,runnable,running,blocked,waiting,time waiting,terminated

Thread thread = new Thread(runnable);

thread.getId()

thread.getName()

thread.setName

thread.getPriority()

threads[i].setPriority(Thread.MIN_PRIORITY);

thread.getState())

猜你喜欢

转载自cc414011733.iteye.com/blog/2293927
今日推荐