JAVA使用多线程实现上传图片,当上传结束后,再经过另一个线程告知下载图片结束,这时候就须要用到synchronized以及wait,notify实现排它,同步通讯,上传图片时,不容许下载,由于此时图片正在上传。java
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(); } } }