static void sleep(long millis):调用此方法后,当前线程放弃 CPU 资源,在指定的时间内,sleep 所在的线程不会获得可运行的机会,此状态下的线程不会释放同步锁。
sleep() 和 yield() 方法的区别:
①、都能使当前处于运行状态的线程放弃 CPU资源,把运行的机会给其他线程
②、sleep 方法会给其他线程运行的机会,但是不考虑其他线程优先级的问题;yield 方法会优先给更高优先级的线程运行机会
③、调用 sleep 方法后,线程进入计时等待状态,调用 yield 方法后,线程进入就绪状态。
join示例:
- public class TestThread1 {
- public static void main(String [] args){
- SubThread1 subThread1=new SubThread1();
- subThread1.start();
- for (int i=0;i<=100;i++){
- System.out.println(Thread.currentThread().getName()+":"+i);
- if(i==20){
- try {
- subThread1.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- class SubThread1 extends Thread{
- @Override
- public void run(){
- for (int i=0;i<=100;i++){
- try {
- Thread.currentThread().sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- }
- }
运行结果:
- main:0
- main:1
- main:2
- main:3
- main:4
- main:5
- main:6
- main:7
- main:8
- main:9
- main:10
- Thread-0:0
- Thread-0:1
- Thread-0:2
- Thread-0:3
- Thread-0:4
- Thread-0:5
- Thread-0:6
- Thread-0:7
- Thread-0:8
- Thread-0:9
- Thread-0:10
- .
- .
- .
- Thread-0:99
- Thread-0:100
- main:11
- main:12
- main:13
- main:14
- main:15
- .
- .
- main:98
- main:99
- main:100
运行结果分析:在main线程中调用线程A的join()方法,此时main线程停止执行,直至A线程执行完毕,main线程再接着join()之后的代码执行
- /**
- * @author: ChenHao
- * @Description:使用两个线程打印1-100,线程1,线程2交替打印
- * 线程通信:如下的三个关键字使用的话,都得在同步代码块或同步方法中。
- * wait():一旦一个线程执行到wait(),就释放当前的锁。
- * notify()/notifyAll():唤醒wait的一个或所有的线程
- * 如果不使用break,程序将不会停止
- * @Date: Created in 10:50 2018/10/29
- */
- public class TestPrintNum {
- public static void main(String [] args){
- PrintNum printNum=new PrintNum();
- Thread thread1=new Thread(printNum);
- Thread thread2=new Thread(printNum);
- thread1.start();
- thread2.start();
- }
- }
- class PrintNum implements Runnable{
- int num=1;
- @Override
- public void run(){
- while (true){
- synchronized (this){
- notify();
- if(num<=100){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+":"+num++);
- }else {
- break;
- }
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- Thread-0:1
- Thread-1:2
- Thread-0:3
- Thread-1:4
- Thread-0:5
- Thread-1:6
- Thread-0:7
- Thread-1:8
- Thread-0:9
- Thread-1:10
- .
- .
- .