线程有五种状态:
新建、可运行、运行中、阻塞、终止
线程通常可以通过两种方法进行创建:继承thread类和实现runnable接口
继承Thread类的话开启线程需要实例化子线程类并调用start()方法:
代码实例:
//创建线程类继承Thread,并重写run()方法 public class MyThread extends Thread{ String name; public MyThread(String name) { this.name = name; } @Override public void run() { System.out.println("线程"+name+"启动了"); } } //实例化线程类并调用其start方法启动线程 public class Test { public static void main(String[] args) { MyThread myThread = new MyThread("01"); myThread.start(); } }
其中Thread类中我们常用sleep、join三种操作线程状态的方法,其中sleep是让当前正在运行线程进入休眠状态,而join则恰恰相反,join是让当前线程以外的其他线程等待该线程的终止,使得该线程能够抢占cpu的资源;
实现runnable接口来创建线程则只需要重写接口中的run方法就行了,但是线程的启动则需要先创建接口实现类的对象并把其作为Thread类的参数并调用Thread类的start方法
代码实例如下:
//实现Runnable接口 public class MyRunnable implements Runnable{ @Override public void run() { System.out.println("线程02启动了"); } } //启动线程 public class Test { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } }
而这两种方法中实现Runnable接口的方式我们更常用一些,原因是一方面java不支持多继承,而另一方面则是实现Runnable接口对于数据的共享也是有好处的;
线程的优先级:
线程的优先级分为十个等级,分别用1到10的整数来表示,其中默认分配的优先级NORM_PRIORITY =5,最低的优先级MIN_PRIORITY =1,最高的优先级MAX_PRIORITY=10
原文:https://www.cnblogs.com/linghan/p/linghan.html