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

JAVA多线程使用synchronized与wait,notify实现排它,同步通信

2019-09-14 07:06 2755 查看

JAVA使用多线程实现上传图片,当上传结束后,再通过另外一个线程告知下载图片结束,这时候就需要用到synchronized以及wait,notify实现排它,同步通信,上传图片时,不允许下载,因为此时图片正在上传。

package com.study;

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{
private boolean isSync = true;
public synchronized void ins(){
try {
while(!isSync){
this.wait();
}
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("正在上传中....");
isSync = false;
this.notify();
}
public synchronized void des(){
while(isSync){
try {
this.wait();
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("下载结束....");
isSync = true;
this.notify();
}
}
}

 

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