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

Java多线程(思维导图)

时间:2019-08-23 10:30:01      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:boolean   throw   asa   obj   cep   except   not   this   oob   

 

 

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-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多线程(思维导图)

标签:boolean   throw   asa   obj   cep   except   not   this   oob   

原文地址:https://www.cnblogs.com/Mufasa/p/11398373.html

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