Java多线程(思维导图)
发布时间:2020-12-15 07:58:14 所属栏目:Java 来源:网络整理
导读:? ? 1, 2, 3,常用函数 Semaphore import java.util.concurrent.Semaphore; Semaphore name= new Semaphore(n);name.acquire(n1);acquire.release(n2); lock中的wait,notify,notifyAll ? ? 4,相关例题 Answer-1: 解决办法: 注意这里使用lock-synchroniz
? ? 1,2,3,常用函数Semaphore import java.util.concurrent.Semaphore; lock中的wait,notify,notifyAll ? ? 4,相关例题Answer-1:解决办法: 注意这里使用lock-synchronized同步以及屏障 package com.cnblogs.mufasa.demo1.Answer1114; class Foo { private boolean firstBlock; private boolean secondBlock; private Object lock=new Object(); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { synchronized(lock){ // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); firstBlock=true; lock.notifyAll(); } } public void second(Runnable printSecond) throws InterruptedException { synchronized(lock){ while(!firstBlock){ lock.wait(); } // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); secondBlock=true; lock.notifyAll(); } } public void third(Runnable printThird) throws InterruptedException { synchronized(lock){ while(!secondBlock){ lock.wait(); } // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } } } ? Answer-2:解决方法: ①定义一个布尔标识符flag,决定轮替输出; ②设置一个lock-synchronized同步; package com.cnblogs.mufasa.demo1.Answer1115; class FooBar { private int n; private boolean flag=false;//定义一个布尔标识位 private Object lock=new Object();//同步锁 public FooBar(int n) { this.n = n; } public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (lock){ while (flag){ lock.wait(); } // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); flag=true; lock.notifyAll(); } } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (lock) { while (!flag) { lock.wait(); } // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); flag=false; lock.notifyAll(); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 如何评论已经包含/ *评论(Java)的整个代码块?
- WC个人项目(Java)
- java – 不允许IntentReceiver组件绑定到服务
- SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper实例详
- java – AtomicInteger是基于JNI实现的吗?
- Java 8 Stream API详解--转
- java – Android应用程序中的秘密密钥的反黑客解决方案?
- Debugging to Understand Finalizer--reference
- java – android.view.InflateException:二进制XML文件行#
- java – 在Intellij中,为什么我要在本地运行Google App Eng