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();
    				}
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    servlet程序开发
    jsp九大内置对象
    git原理教程
    jsp基础语法_Scriptlet_基本指令
    06_mysql多表查询
    05_mysql单表查询
    04_mysql增删改操作
    03_mysql索引的操作
    01_mysql数据库操作和基本数据类型
    生成器
  • 原文地址:https://www.cnblogs.com/SuperBing/p/3012404.html
Copyright © 2011-2022 走看看