创建线程
- 继承Thread类
- 实现Runnable接口
(1)继承Thread类
package Thread;public class MyThread extends Thread{@Overridepublic void run(){super.run();System.out.println("MyThread");}
}public static void main (String[] args){MyThread myThread = new MyThread();myThread.start();//耗时大System.out.println("运行结束!");}------------------
运行结束!
MyThread
-------------------
线程的执行先后跟代码执行顺序无关
public static void main (String[] args){MyThread myThread = new MyThread();myThread.start();//耗时大Thread.sleep(200);System.out.println("运行结束!");}
------------------
MyThread
运行结束!
-------------------
(2)实现Runnable接口
创建的线程类已经有一个父类了,就不能在继承Thread类,因为java不支持多继承
就只能实现Runnable接口
package
public class MyRunnable implements Runnable{@Overridepublic void run(){System.out.println("运行中");}
}public static void main (String[] args){Runnable runnable = new MyRunnable();Thread thread = new Thread(runnable); thread.start();//耗时大System.out.println("运行结束!");}
------------------
运行结束!
运行中
-------------------