一、线程的状态
1、就绪状态:当线程调用了start()方法,该线程就进入了就绪状态,等待JVM里线程调度器的调度。
2、运行状态:如果就绪状态的线程获取了CPU,就可以执行run()。
3、阻塞状态 : 如果一个线程执行了sleep()、wait()等方法,就进入了阻塞状态。
二、创建线程
1、继承Thread类
例
public class Test25 extends Thread{ String name; Test25(String name){ this.name = name; } public static void main(String args[]){ Thread thread1 = new Test25("我是线程1"); Thread thread2 = new Test25("我是线程2"); System.out.println(Test25.currentThread().getName()); thread1.start(); thread2.start(); } @Override public void run() { System.out.println(name+"线程开始执行"); } }
2、实现Runnable接口
例
public class Test24 implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() +"正在执行"); } public static void main(String args[]){ Thread thread = new Thread(new Test24(),"线程1"); thread.start(); Thread thread1 = new Thread(new Test24(),"线程2"); thread1.start(); } }
3、为什么不直接执行run()方法呢?
例
public class Test25 extends Thread{ String name; Test25(String name){ this.name = name; } public static void main(String args[]){ Thread thread1 = new Test25("我是线程1"); Thread thread2 = new Test25("我是线程2"); thread2.start(); thread1.run(); System.out.println(thread1.isAlive()); System.out.println(thread2.isAlive()); } @Override public void run() { System.out.println(name+"线程开始执行"); } }结果:直接执行run()方法,并没有建立该线程,所以需调用start()方法来新建线程
备注:由于JAVA语言的单继承机制,使用实现Runnable接口具有更高的灵活性。