ITPub博客

首页 > > > 线程同步,synhronized,

线程同步,synhronized,

作者:doudourabbit 时间:2019-08-28 14:29:02 0 删除 编辑

要求主线程执行100次,子线程执行10次,主线程执行100次,子线程执行10次。。。循环

代码如下:

public class Test_02 {

public static void main(String[] args){
    
    MeThread me = new MeThread();
    Thread t = new Thread(me);
    t.start();

    boolean flag = true;
    int i = 1;
    synchronized (me) {
        
        while (flag) {
            System.out.println(Thread.currentThread().getName() + i);
            i++;
            if (i % 100 == 0) {
                try {
                    Thread.currentThread().wait();
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }finally {
                    System.out.println("===========");
                    me.notify();//Thread.currentThread().notifyAll();也不行
                }
            }
        }
    }
}
}

class MeThread implements Runnable {
@Override
public synchronized void run() {
int i = 0;

    boolean flag = true;
    while (flag) {
        System.out.println(Thread.currentThread().getName() + i);
        i++;
        if (i % 10 == 0) {
            try {
                Thread.currentThread().wait();
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }finally {
                System.out.println("===========");
                
                this.notify();//Thread.currentThread().notifyAll();也不行
            }
        }
    }
}
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4809/viewspace-3164044/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-25

  • 博文量
    193
  • 访问量
    1438