一、Thread类的构造方法
public Thread();
public Thread (Runnable target);
public Thread (Runnable target,String name);
public Thread (String name);
public Thread (ThreadGroup group,Runnable target);
public Thread (ThreadGroup group,Runnable target,String name);
public Thread (ThreadGroup group,String name);
二、Java中提供了2种创建线程的方法:
(1) 继承Thread类(java.lang.Thread)
public class Thread extends Object implements Runnable
这种方法是将类声明为Thread
的子类。该子类应重写Thread
类的run
方法。接下来可以分配并启动该子类的实例。
实例一:
public class ThreadTest02 extends Thread{ public void run(){ for(int i=0; i<10; i++){ System.out.println("线程"+Thread.currentThread().getName()+"extends Thread is running..."+i); } System.out.println("线程"+Thread.currentThread().getName()+"执行结束,退出!"); } public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new ThreadTest02(); t1.setName("T1"); Thread t2 = new ThreadTest02(); t2.setName("T2"); t1.start(); t2.start(); } }
运行结果:
(2)利用Runnable接口(java.lang.Runnable)
这种方法是声明实现Runnable
接口的类。该类然后实现run
方法。然后可以分配该类的实例,在创建Thread
时作为一个参数来传递并启动
实例二:
public class ThreadTest02 implements Runnable{ public void run(){ for(int i=0; i<10; i++){ System.out.println("线程"+Thread.currentThread().getName()+"implements Runnable interface is running..."+i); } System.out.println("线程"+Thread.currentThread().getName()+"执行结束,退出!"); } public static void main(String[] args) { // TODO Auto-generated method stub ThreadTest02 t = new ThreadTest02(); Thread thread = new Thread(t); thread.start(); } }
运行结果: