zoukankan      html  css  js  c++  java
  • 线程同步

    package day12.javaAdvance.homework.Thread;
    
    public class ThreadTest {
    	public static void main(String[] args) {
    
    		Object obj = new Object();
    		printNumber1 pn = new printNumber1(obj);
    		pn.start();
    		printChar1 pc = new printChar1(obj);
    		Thread t = new Thread(pc);
    		t.start();
    	}
    }
    
    class printNumber1 extends Thread {
        //创建一个临界资源obj
    	Object obj = new Object();
    
    	public printNumber1(Object obj) {
    		this.obj = obj;
    	}
    
    	public void run() {
    		// 同步代码块:
    		synchronized (obj) {
    			for (int i = 1; i <= 26; i++) {
    				System.out.println(2 * i - 1);
    				System.out.println(2 * i);
    				obj.notifyAll();// 释放/唤醒等待队列所有对象
    				try {
    					obj.wait();// 等待队列
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    
    class printChar1 implements Runnable {
    
    	Object obj = new Object();
    
    	public printChar1(Object obj) {
    		this.obj = obj;
    	}
    
    	public void run() {
    		// 同步代码块:
    		synchronized (obj) {
    			for (char i = 'A'; i <= 'Z'; i++) {
    				System.out.println(i);
    				obj.notifyAll();
    				try {
    					obj.wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    1043. 输出PATest(20)
    1042. 字符统计(20)
    1041. 考试座位号(15)
    1040. 有几个PAT(25)
    1035. 插入与归并(25)
    栈:火车进站
    ABC Fennec VS. Snuke
    费解的开关
    最短Hamilton路径
    built?
  • 原文地址:https://www.cnblogs.com/SuperBing/p/3012404.html
Copyright © 2011-2022 走看看