Thread类的常用方法
package com.attest.java1;
/*
* Thread的常用方法
* 1.start(),启动线程并执行相应的run()方法
* 2.run():子线程要执行的代码放入run()方法中
* 3.currentThread():静态的,调取当前的线程
* 4.getName():获取此线程的名字
* 5.setName():设置此线程的名字
* 6.yield(): 调用此方法的线程释放当前CPU的执行权
* 7.join():在A线程中调用B线程的join()方法。
* 表示:当执行到此方法。A线程停止执行,直至B线程执行完毕,A线程再接着执行jonin()之的的代码执行
* 8.isAlive():判断当前纯种是否还存活
* 9.sleep(long millis): 显示的让当前线程眨眼1毫秒
* 10.线程通信 : wait() notify() notifyAll()
*
* 11.设置线程的优先级
* getPriority(): 返回线程的优先级
* setPriority(int newPriority) : 改变线程的优先级
* 线程创建时继承父线程的优先级
*/
class SubThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// try {
// /*
// * 方法重写的规则 :子类的方法不能比父类抛更大的异常 ,而在这Thread父类里,
// * 根本就没有抛出异常
// */
// Thread.currentThread().sleep(1000);//为什么 这个异常不能使用Throws
//
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + " : " +Thread.currentThread().getPriority() +" : "+ i);
}
}
}
public class TestThread1 {
public static void main(String[] args) {
SubThread1 st1 = new SubThread1();
st1.setName("子线程1");
st1.setPriority(Thread.MAX_PRIORITY);//可以写数字
st1.start();
Thread.currentThread().setName("=========主线程");
for (int i = 0; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " +Thread.currentThread().getPriority() +" : "+ i);
// if(i % 10 ==0){//当 i 是10的倍数时
// Thread.currentThread().yield();//强制释放当前CPU的执行权
// }
if (i == 20) {
try {
st1.join();//强制让st1线程执行进来。只有当st1线程执行完,才可以执行其他线程。这里指的是主线程
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(st1.isAlive());//判断当前(st1)纯种是否还存活
}
}
---------------------------------------------------------------------------------------------
线程的优先级(线程的调度)
* 调度的策略
-->时间片
-->抢占式:高优先级的纯种抢占CPU
* Java的调度方法
-->同优先级的线程组成先进先出队列(先到先服务),使用时间片策略
-->对高优先级,使用优先调度的抢占式策略
线程的优先级
* 线程的优先级控制
》MAX_PRIORITY(10 )
》MIN_PRIORITY(1 )
》NORM_PRIORITY(5 )
* 涉及的方法
》getPriority():返回线程的优先级
》setPriority(int newPriority) :改变线程的优先级
》线程创建时继承父线程的优先级