我们来认识几个线程的方法
sleep() yield() join()
package com.tianhao;public class Sleep_Yield_Join {public static void main(String[] args) {//testSleep();//testYield();testJoin();} /*Sleep,意思就是睡眠,当前线程暂停一段时间让给别的线程去运行。Sleep是怎么复活的?由你的睡眠时间而定,等睡眠到规定的时间自动复活*/static void testSleep() {new Thread(()->{for(int i=0; i<100; i++) {System.out.println("A" + i);try {Thread.sleep(500);//TimeUnit.Milliseconds.sleep(500)} catch (InterruptedException e) {e.printStackTrace();}}}).start();}/*Yield,就是当前线程正在执行的时候停止下来进入等待队列(就绪状态,CPU依然有可能把这个线程拿出来运行),回到等待队列里在系统的调度算法里头呢还是依然有可能把你刚回去的这个线程拿回来继续执行,当然,更大的可能性是把原来等待的那些拿出一个来执行,所以yield的意思是我让出一下CPU,后面你们能不能抢到那我不管*/static void testYield() {new Thread(()->{for(int i=0; i<100; i++) {System.out.println("A" + i);if(i%10 == 0) Thread.yield();}}).start();new Thread(()->{for(int i=0; i<100; i++) {System.out.println("------------B" + i);if(i%10 == 0) Thread.yield();}}).start();}/*join, 意思就是在自己当前线程加入你调用Join的线程(),本线程等待。等调用的线程运行完了,自己再去执行。t1和t2两个线程,在t2的某个点上调用了t1.join,它会跑到t1去运行,t2等待t1运行完毕继续t1运行(自己join自己没有意义) */static void testJoin() {Thread t1 = new Thread(()->{for(int i=0; i<100; i++) {System.out.println("A" + i);try {Thread.sleep(500);//TimeUnit.Milliseconds.sleep(500)} catch (InterruptedException e) {e.printStackTrace();}}});Thread t2 = new Thread(()->{try {t1.join();} catch (InterruptedException e) {e.printStackTrace();}for(int i=0; i<100; i++) {System.out.println("A" + i);try {Thread.sleep(500);//TimeUnit.Milliseconds.sleep(500)} catch (InterruptedException e) {e.printStackTrace();}}});t1.start();t2.start();}
}
JAVA的6中线程状态:
如下图:
synchronized:经过操作系统的调度
线程状态测试代码:
package com.tianhao;import com.tianhao.SleepHelper;import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;public class ThreadState {static class MyThread extends Thread {@Overridepublic void run() {System.out.println("2: " + this.getState());for (int i = 0; i < 10; i++) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.print(i + " ");}System.out.println();}}public static void main(String[] args) throws Exception {Thread t1 = new MyThread();System.out.println("1: " + t1.getState());t1.start();t1.join();System.out.println("3: " + t1.getState());Thread t2 = new Thread(() -> {try {LockSupport.park();System.out.println("t2 go on!");TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}});t2.start();TimeUnit.SECONDS.sleep(1);System.out.println("4: " + t2.getState());LockSupport.unpark(t2);TimeUnit.SECONDS.sleep(1);System.out.println("5: " + t2.getState());final Object o = new Object();Thread t3 = new Thread(()->{synchronized (o) {System.out.println("t3 得到了锁 o");}});new Thread(()-> {synchronized (o) {SleepHelper.sleepSeconds(5);}}).start();SleepHelper.sleepSeconds(1);t3.start();SleepHelper.sleepSeconds(1);System.out.println("6: " + t3.getState());}
}
上一篇:TCP协议原理三
下一篇:Hermite矩阵的酉对角化