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(); } } }