ITPub博客

首页 > 应用开发 > > 线程同步,synhronized,锁

线程同步,synhronized,锁

作者:dapan 时间:2019-08-21 10:17:09 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/758/viewspace-3132029/ ,如需转载,请注明出处,否则将追究法律责任。

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

注册时间:2020-08-07

  • 博文量
    4504
  • 访问量
    87231