您的位置:首页 > 编程语言 > Java开发

JAVA多线程使用Lock与Condition实现排它,同步通信

2019-09-14 07:06 2663 查看
package com.study;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo {

public static void main(String[] args) {
Demo demo = new Demo();
final OutPutClass putPutClass = demo.new OutPutClass();
Thread thread = new Thread(new Runnable() {

@Override
public void run() {
while (true) {
putPutClass.ins();
}
}
});
thread.start();

Thread thread2 = new Thread(new Runnable() {

@Override
public void run() {
while (true) {
putPutClass.des();
}
}
});
thread2.start();
}

class OutPutClass {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
private boolean isSync = true;

public void ins() {
lock.lock();
try {
while (!isSync) {
condition.await();
}
Thread.sleep(1000L);
System.out.println("正在上传中....");
isSync = false;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void des() {
lock.lock();
try {
while (isSync) {
condition.await();
Thread.sleep(1000L);
}
System.out.println("下载结束....");
isSync = true;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java
相关文章推荐