setPriority(int newPriority) 更改线程的优先级
Static void sleep(long millis) 在指定的毫秒数内让当前正在执行的线程休眠
Void join() 等待该线程终止
Static void yield() 暂停当前正在执行的线程对象,并执行其他线程
Void interrupt() 中断线程
Boolean isAlive() 测试线程是否处于活动状态
线程的优先级
线程优先级有1–10表示,1最低,默认优先级为5
优先级高德线程获得CPU资源的概率较大
public class MyRunnable implements Runnable{
public void run() {
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
测试类
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),”线程a”);
Thread t2 = new Thread(new MyRunnable(),”线程b”);
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
线程的强制执行
让线程暂时休眠指定时长,线程进入阻塞状态
睡眠时间过后线程会再进入可运行状态
Public static void sleep(long millis)
Millis为休眠时长,以毫秒为单位
调用sleep()方法需处理InterruptedException异常
Join方法
创建类
public class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+”运行”+i);
}
}
}
测试类
public class TestJionDemo {
public static void main(String[] args) {
System.out.println(“—-线程强制执行—-“);
//1.创建线程对象
Thread temp = new Thread(new MyRunnable(),”temp”);
temp.start();
for(int i=0;i<20;i++){
//当主线程执行到i=5是,暂停主线程,让子线程temp执行,完毕之后,主线程在继续执行
if(i==5){
try {
temp.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行: "+i+"秒");
}
}
}
线程的礼让
暂停当前线程,允许其他具有相同优先级的线程获得运行机会
该线程处于就绪状态,不转为阻塞状态
只提供一种可能,但是不能保证一定会让礼让实现
public class MyRunnable implements Runnable{
public void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+”运行”+i);
//当i==3时,县城里让,当前线程将CPU资源让出
if(i==3){
Thread.yield();
System.out.print(“线程礼让: “);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
测试类
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),”线程a”);
Thread t2 = new Thread(new MyRunnable(),”线程b”);
t1.start();
t2.start();
}
}
线程的五个状态
创建,就绪,阻塞,运行,死亡
线程调度的方法
setPriority(int grade)
sleep(long millis)
Join()
yield()