1.Thread类常用方法
- start():启动线程并执行相应的run()方法
- run():子线程要执行的代码放入run()方法中
- currentThread():静态的,调取当前线程
- getName():获取此线程的名字
- setName():设置此线程的名字
- yield():调用此方法的线程释放当前CPU的执行权
- join():在A线程中调用B线程的join()方法,表示当执行到此方法,A线程停止执行,指导B线程执行完毕,A线程在接着join()之后的代码执行
- isAlive():判断线程是否还存活
- sleep(long lon):显示的让当前线程睡眠lon毫秒
2. 线程通信:wait() notify() notifyAll()
后续写线程通信的时候补充。
3.线程的调度
1. 调度策略
- 时间片
- 抢占式:高优先级的线程抢占CPU
2.Java的调度方法
- 同优先级线程组成先进先出队列(先到先服务),使用时间片策略
- 对高优先级,使用优先调度的抢占式策略
3.线程的优先级
- 线程的优先级控制
① MAX_PRIORITY(10);
② MIN _PRIORITY (1);
③ NORM_PRIORITY (5); - 涉及的方法:
① getPriority() :返回线程优先值
② setPriority(int newPriority) :改变线程的优先级
③ 线程创建时继承父线程的优先级
4.Demo
class SubThread extends Thread{
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName()+ ":"+Thread.currentThread().getPriority()+":"+i);
}
}
}
public class TestThreadMethod {
public static void main(String[] args) {
SubThread st = new SubThread();
st.setName("子线程");
st.setPriority(Thread.MAX_PRIORITY);
st.start();
Thread.currentThread().setName("主线程");
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName()+ ":"+Thread.currentThread().getPriority()+":"+i);
}
System.out.println(st.isAlive());
}
}