zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java线程等待与唤醒案例(wait和notify方法使用)

JAVA案例方法线程 等待 WAIT 唤醒 notify
2023-09-14 09:02:03 时间
package com.zhangxueliang.day_20191031;

public class WaitNotify {
	
	final static char[] cI = "1234567".toCharArray();
	final static char[] cC = "ABCDEFG".toCharArray();
	final static Thread t1 = null;
	final static Thread t2 = null;
	final static Object obj = new Object();
	
	public static void main(String[] args) {
		new Thread(()->m1()).start();
		new Thread(()->m2()).start();
	}
	
	public static void m1(){
		synchronized(obj){
			for (char c:cI) {
				System.out.print(c);
				try {
					obj.notify();
					obj.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			obj.notify();
		}
	}
	public static void m2(){
		synchronized(obj){
			for (char c:cC) {
				System.out.print(c);
				try {
					obj.notify();
					obj.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			obj.notify();
		}
	}
}