码迷,mamicode.com
首页 > 编程语言 > 详细

多线程同步 wait notify

时间:2014-05-17 00:21:52      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

bubuko.com,布布扣
package test;

public class Test implements Runnable{

    public static int j =0;
    @Override
    public void run() {
            synchronized (this) {
                while (j<30) {
                    System.out.println(Thread.currentThread().getName() + ": " + ++j);  
                    if (j % 3 == 0 && 0 != j) {
                        try {
                            this.notify(); // 唤醒另外一个线程  
                            this.wait(); // 暂时释放资源  
                        } catch (InterruptedException e) {
                            e.printStackTrace();  
                        } 
                    }
                }
            }
    }
    public static void main(String[] args) {
        Runnable run = new Test();
        Thread thread1 = new Thread(run);
        Thread thread2 = new Thread(run);
        
        thread1.start();
        thread2.start();
    }
}
bubuko.com,布布扣
bubuko.com,布布扣
Thread-1: 1
Thread-1: 2
Thread-1: 3
Thread-0: 4
Thread-0: 5
Thread-0: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9
Thread-0: 10
Thread-0: 11
Thread-0: 12
Thread-1: 13
Thread-1: 14
Thread-1: 15
Thread-0: 16
Thread-0: 17
Thread-0: 18
Thread-1: 19
Thread-1: 20
Thread-1: 21
Thread-0: 22
Thread-0: 23
Thread-0: 24
Thread-1: 25
Thread-1: 26
Thread-1: 27
Thread-0: 28
Thread-0: 29
Thread-0: 30
bubuko.com,布布扣

简单的多线程同步的例子,理解:

Thread0先获得对象锁this,THread1在等待,当Thread0进入this.notify(); // 唤醒另外一个线程  此行时,唤醒Thread1,但由于Thread0仍然占据着this对象锁,Thread1还不会进入同步代码块,直到Thread0运行到this.wait(),此时Thread0释放this对象锁,堵塞,Thread1获得对象锁,进入同步代码块,循环...

多线程同步 wait notify,布布扣,bubuko.com

多线程同步 wait notify

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/fengjian/p/3724977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!