zoukankan      html  css  js  c++  java
  • java

    public class T {
        
        private static int a =1;//1代表线程1 2线程2
        
        public static void main(String[] args) {
            
            final T t = new T();
            
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    synchronized (t) {
                        for(int i=1;i<=10;i++){
                            if(i==6){
                                    try {
                                        a=2;//切换线程2
                                        t.wait();//线程1等待,并释放了对象的锁
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            System.out.println(Thread.currentThread().getName()+":"+i);
                        }                                            
                    }
                }
            }).start();;
            
            new Thread(new Runnable(){
    
                @Override
                public void run() {
                    synchronized (t) {
                        if(a!=2){//没有轮到,进入等待
                            try {
                                t.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("hello");
                        t.notifyAll();
        
                    }
                    
                }
                
            }).start();
    
        }        
    }

     结果如下:

    Thread-0:1
    Thread-0:2
    Thread-0:3
    Thread-0:4
    Thread-0:5
    Thread-1:hello
    Thread-0:6
    Thread-0:7
    Thread-0:8
    Thread-0:9
    Thread-0:10

  • 相关阅读:
    进度条4
    构建之法读书笔记02
    进度条3
    个人作业四则运算2测试
    个人作业3
    从小工到专家阅读笔记01
    个人冲刺07
    个人冲刺06
    个人冲刺05
    学习进度条08
  • 原文地址:https://www.cnblogs.com/GotoJava/p/6743043.html
Copyright © 2011-2022 走看看