SLEEP

sleep 意思是睡眠,当前线程暂停一段时间让给别的线程去运行。sleep是怎么复活的?由你的睡眠时间而定,等睡眠到规定的时间自动复活,CPU 没有线程的概念,会不断的从内存中获取指令去执行,睡眠的意思就是当前线程让出cpu 由其他线程去执行。

  1. static void testSleep() {
  2. new Thread(()->{
  3. for(int i=0; i<100; i++) {
  4. System.out.println("A" + i);
  5. try {
  6. Thread.sleep(500);
  7. //TimeUnit.Milliseconds.sleep(500)
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }).start();
  13. }
  14. public static void main(String[] args) throws InterruptedException {
  15. sleep();
  16. // yield();
  17. // join();
  18. }

YIELD

yield 让出当前cpu进入线程的等待队列,下一次能不能进入线程看自己能不能抢到,当yield让出cpu后后续更大可能是将等待队列里面的线程拿过来进行执行。暂时没有应用场景。

  1. static void yield(){
  2. new Thread(()->{
  3. for (int i = 0; i < 100; i++) {
  4. try {
  5. if (i % 10 == 0) {
  6. Thread.yield();
  7. }
  8. System.out.println("i am thread a");
  9. TimeUnit.SECONDS.sleep(1);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }).start();
  15. new Thread(()->{
  16. for (int i = 0; i < 100; i++) {
  17. try {
  18. if (i % 10 == 0) {
  19. Thread.yield();
  20. }
  21. System.out.println("i am thread b");
  22. TimeUnit.SECONDS.sleep(1);
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }).start();
  28. }
  29. public static void main(String[] args) throws InterruptedException {
  30. // sleep();
  31. yield();
  32. //join();
  33. }

JOIN

在当前线程加入你调用join的线程,此处是t1 线程加入到t2线程里面去了,当t2线程执行到 join的时候,就会去执行t1线程,只有t1 线程执行完成之后才会接着执行t2线程。

  1. static void join() throws InterruptedException {
  2. Thread t1 = new Thread(() -> {
  3. for (int i = 0; i < 100; i++) {
  4. try {
  5. System.out.println("i am thread a");
  6. TimeUnit.SECONDS.sleep(1000);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. }
  11. });
  12. Thread t2 = new Thread(() -> {
  13. for (int i = 0; i < 100; i++) {
  14. try {
  15. System.out.println("i am thread b");
  16. t1.join();
  17. System.out.println("i am thread b");
  18. TimeUnit.SECONDS.sleep(1);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. });
  24. t1.start();
  25. TimeUnit.SECONDS.sleep(10);
  26. t2.start();
  27. }
  28. public static void main(String[] args) throws InterruptedException {
  29. // sleep();
  30. // yield();
  31. join();
  32. }