回顾:
在日常开发中我们常用实现Runnable接口,但是在Runnable接口中只有run方法,所以在启动线程的时候我们必须将Runnable对象转换成Thread类的对象,从而可以使用.start()方法来启动线程; Thread th1=new Thread(Runnable对象,线程名字);
接下来学习一下线程常见的API
一、设置线程的优先级 .setpriority()
注意:优先级只是一个建议,但不能百分百保证
th1.setpriority(10); //1-10
th2.setpriority(2);
二、线程休眠,就是暂停的意思,单位是毫秒 .sleep()
Thread.sleep(1000);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
三、依赖关系:强制执行、现场礼让
——>强制执行
join:强制执行调动join()的线程,阻塞当前正在执行的线程
实例
public class ThreadDemo implements Runnable{
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
//这里有两个线程一个是main主线程 一个是线程th1
//
public static void main(String[] args){
ThreadDemo t1=new ThreadDemo();
Thread th1=new Thread(t1,"T1");
th1.start;
for(int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
if(i==3){
th1.join();//当main线程正在执行时(执行到i=3时,th1强制抢夺执行)
}
}
}
}
——>线程的礼让:
yield(),礼让仅仅是一种尽可能的事件,并不是百分百执行
public void run() {
for(int i =0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
if(i==3){
Thread.yield();
System.out.println("礼让。。。。");
}
}
}
//线程th1:执行“T1:数字”
//线程main: 执行"main:数字"
public static void main(String[] args) throws InterruptedException {
ThreadDemo03 t1=new ThreadDemo03();
Thread th1=new Thread(t1,"T1");
th1.start();
ThreadDemo03 t2=new ThreadDemo03();
Thread th2=new Thread(t2,"T2");
th2.start();
注意:并不是所有的线程都是通过start()启动,除了main()线程