线程通信

 

主要涉及java.lang.Object 中三个方法(只能在synchronized方法或者synchronized代码块中使用,否则会报java.lang.illegalMonitorStateException异常)

  • wait():释放锁,让当前侠线程挂起,等候再次对资源的访问,
  • notufy():唤醒优先级最高的线程,
  • notifyAll():唤醒正在排队等待的资源的所有线程

例如 让两个线程交替打印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();
    }
}

 

posted @ 2018-10-13 17:42  wsjun  阅读(125)  评论(0编辑  收藏  举报