文章目录
1、创建多线程
- 继承Thread类,重写 run()方法
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i%2==0) System.out.println(this.getName());
}
}
- 实现Runnable接口,重写run()方法,将这个实例传入Thread类
public static void main(String[] args) {
Thread thread = new Thread(new Task());
//start调用thread的run(),thread的run()又调用了Task的run()
thread.start();
}
class Task implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
推荐使用实现runnable接口:
- 解决类的单继承问题。
- 多线程共享数据更适合处理
注意:Thread类也实现了runnable接口,其中的run()方法也是实现runnable接口的
2、方法
- public void start() : 调用该线程,并且让jvm调用Thread类及子类的run()方法
- public static void yield():暗示调度器当前线程愿意暂停执行,从而让其他等待线程获取执行权。(但是执行后,其他线程不一定能获取执行权)
- public void join() :在线程A调用线程B对象的join方法时,线程A将被阻塞,
直到线程B运行完(低优先级的线程也可以获得执行),再次执行。 - public static void sleep(long millis):让当前线程休眠。注意:sleep方法只是让出了cpu的执行权,并不会释放同步资源锁。
3、线程的生命周期
2、就绪、运行、阻塞的区别
就绪:可以被cpu调度
运行:正在被cpu调度
阻塞:无法被cpu调度
4、线程的调度
1、线程调度策略
线程的调度有两种策略:
- 时间片:线程之间交互使用cpu
- 抢占式:高优先级的线程抢占cpu
相同优先级的线程组成队列,使用时间片策略
不同优先级的线程之间采用抢占式策略,高优先级的优先调度。
2、线程的优先级
/**
* The minimum priority that a thread can have.
*/
public static final int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public static final int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public static final int MAX_PRIORITY = 10;
3、优先级set、get方法
- public final void setPriority( int newPriority )
- public final int getPriority()
4、注意点
- 线程创建时继承父线程的优先级
- 线程的优先级只是表示获得调度的概率大小,低优先级获得调度的概率小,高优先级大。所以低优先级不一定比高优先级晚调度。