JAVA创建线程的两种方式:实现Runnable接口和扩展Thread类

线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程。JAVA创建线程的两种基本方式为实现Runnable接口和扩展Thread类。

一、实现Runnable接口

java.lang.Runnable接口只有一个run()方法,实现Runnable接口的线程启动时会自动运行run()方法。Runnable接口源码如下:

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
package com.xieyincai.thread;

public class MyRunnable implements Runnable {

	public void run() {
		System.out.println("Thread is running ...");
	}
}
package com.xieyincai.thread;

public class Main1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		for(int i=0; i<5; i++) {
			MyRunnable runable = new MyRunnable();
			Thread t = new Thread(runable);
			t.start();
		}
	}

}

二、扩展Thread类

实际上,Thread类也实现了Runnable接口(public class Thread implements Runnable)

package com.xieyincai.thread;

public class MyThread extends Thread {

	public void run() {
		System.out.println("Thread is running ...");
	}
}
package com.xieyincai.thread;

public class Main2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		for(int i=0; i<5; i++) {
			Thread t = new MyThread();
			t.start();
		}
	}

}

注:Thread线程调用start()方法启动线程,状态变成就绪态,一旦调度并获得CPU资源,线程就进入运行态,并运行run()方法。

Leave a Reply

Your email address will not be published. Required fields are marked *