标签:current 线程通信 释放 time oid port 线程 sleep tst
主要涉及java.lang.Object 中三个方法(只能在synchronized方法或者synchronized代码块中使用,否则会报java.lang.illegalMonitorStateException异常)
例如 让两个线程交替打印1-100
import static java.lang.Thread.sleep; /** * @author: wsj * @date: 2018/10/13 * @time: 17:27 */ class PrintNum implements Runnable{ int num = 1; @Override public void run() { while(true){ synchronized (this){ notify(); if(num <= 10) { try { sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + num); num++; try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } public class miantest { public static void main(String[] args) { PrintNum p = new PrintNum(); Thread t1 = new Thread(p); Thread t2 = new Thread(p); t1.setName("ji"); t2.setName("yi"); t1.start(); t2.start(); } }
标签:current 线程通信 释放 time oid port 线程 sleep tst
原文地址:https://www.cnblogs.com/wsjun/p/9783596.html