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

mac2024-10-07  47

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

 

最新回复(0)