一.线程的常用方法
1.线程的优先级
Thread thread = new Thread(myRunnable); thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级
MAX_PRIORITY优先级高,MIN的优先级低
2.睡眠当前线程
class MyRunnable implements Runnable{ public void run() { for(int i=0;i<10;i++){ System.out.println("新开的线程"+i); } } } public class Demo2 { public static void main(String[] args) throws InterruptedException { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级 thread.start(); Thread.sleep(1000*10);//线程睡眠,想要哪个线程睡眠,在哪个线程使用改方法 for(int i=0;i<10;i++){ System.out.println("主线程"+i); } } }
注意是Thread类去调用sleep方法
3.设置让步
线程让步就是让出cpu资源,重新回到就绪状态,还是可以重新竞争资源,不会像sleep方法一样线程进入阻塞状态
class MyRunnable implements Runnable{ public void run() { for(int i=0;i<10;i++){ System.out.println("新开的线程"+i); } } } public class Demo2 { public static void main(String[] args) throws InterruptedException { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.setPriority(Thread.MAX_PRIORITY);//线程的优先级 thread.start(); Thread.yield();//线程让步(让出cpu资源) 但是实际不能保证改线程让步,因为释放资源后他还是会重新竞争 for(int i=0;i<10;i++){ System.out.println("主线程"+i); } } }
4.合并
t.join()
线程A合并进入线程B,B线程会进入阻塞状态直到线程A执行完毕。
class JoinThread implements Runnable{ public void run() { for(int i=0;i<10;i++){ System.out.println("新开的线程"+i); } } } public class JoinTest { public static void main(String[] args) throws InterruptedException { System.out.println("=====主线程开始====="); Thread t = new Thread(new JoinThread()); t.start(); t.join(); System.out.println("=====主线程结束====="); } }
5.守护线程
线程A在主线程中设置为守护线程,当主线程结束时,不管线程A是否执行完,线程A也会结束
class DemanThread implements Runnable{ public void run() { for(int i=0;i<100;i++){ System.out.println("新开的线程"+i); } } } public class DemanTest { public static void main(String[] args) { Thread t = new Thread(new DemanThread()); t.setDaemon(true); t.start(); for(int i=0;i<30;i++){ System.out.println("主线程"+i); } } }
二.线程状态
new的时候为new
start后转为runnable
获取到cpu资源转为running
yeild让步使running状态退回runnable状态
join,sleep均可使线程阻塞,从running转为blocked