继承Thread类,然后重写run方法.(由于Java单继承的特性,这种方式用的比较少)
public class MyThread extends Thread { public MyThread() { } public void run() { for(int i=0;i<10;i++) { System.out.println(Thread.currentThread()+":"+i); } } public static void main(String[] args) { MyThread mThread1=new MyThread(); MyThread mThread2=new MyThread(); MyThread myThread3=new MyThread(); mThread1.start(); mThread2.start(); myThread3.start(); } } (2).实现Runnable()接口定制执行目标(target)类,实现其run()方法推荐此方式。两个特点:
a.覆写Runnable接口实现多线程可以避免单继承局限
b.实现Runnable()可以更好的体现共享的概念
c.当执行目标类实现Runnable接口,此时执行目标(target)类和Thread是代理模式(子类负责真是业务的操作,thread负责资源调度与线程创建辅助真实业务。
public class MyTarget implements Runnable{ public static int count=20; public void run() { while(count>0) { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"-当前剩余票数:"+count--); } } public static void main(String[] args) { MyThread target=new MyTarget(); Thread mThread1=new Thread(target,"线程1"); Thread mThread2=new Thread(target,"线程2"); Thread mThread3=new Thread(target,"线程3"); mThread1.start(); mThread2.start(); myThread3.start(); } } (3).实现Callable接口创建多线程(JDK1.5)