线程生命周期:创建、就绪、运行、阻塞、死亡
创建线程的3种方式:
1、继承Thread类
(1)自定义类MyThread继承Thread类。
(2)MyThread类里面重写run()方法。
(3)创建对象。
(4)启动线程。
2、实现Runnable接口
(1)自定义类MyRunnable实现Runnable接口。
(2)重写run()方法。
(3)创建MyRunnable类的对象。
(4)创建Thread类的对象,并把步骤(3)的对象作为构造参数传递。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
1、 public class { public static void main(String[] args){ MyThread my1 = new MyThread(); MyThread my2 = new MyThread(); my1.start(); my2.start(); } }
public class MyThread extends Thread{ public void run(){ for(int x=0;x<10;x++){ System.out.println(getName()+":"+x); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
2、 public class MyRunnableDemo{ public static void main(String[] args){ MyRunnable my = new MyRunnable(); Thread t1 = new Thread(my); Thread t1 = new Thread(my); t1.start(); t2.start(); } }
public class MyMyRunnale implements Thread{ public void run(){ for(int x=0;x<10;x++){ System.out.println(Thread.currentThread().getName()+":"+x); } } }
|
limaodeng
近期评论