在Java中,IO和多線程是非常重要的知識點,下面是一個簡單的快遞柜程序的代碼實現。
import java.util.ArrayList; import java.util.List; public class ExpressBox { public static void main(String[] args) { ListpackageList = new ArrayList<>(); for (int i = 1; i<= 20; i++) { packageList.add("package" + i); } Thread senderThread = new Thread(new Sender(packageList)); senderThread.start(); Thread receiverThread = new Thread(new Receiver(packageList)); receiverThread.start(); } static class Sender implements Runnable { private List packageList; public Sender(List packageList) { this.packageList = packageList; } @Override public void run() { synchronized (packageList) { while (packageList.size() >0) { try { packageList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i<= 20; i++) { String pkg = "package" + i; packageList.add(pkg); System.out.println("Sender: package" + i + " has been sent to the box."); packageList.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } static class Receiver implements Runnable { private List packageList; public Receiver(List packageList) { this.packageList = packageList; } @Override public void run() { synchronized (packageList) { while (packageList.size()< 20) { try { packageList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i<= 20; i++) { String pkg = packageList.get(i - 1); packageList.remove(pkg); System.out.println("Receiver: " + pkg + " has been picked up from the box."); packageList.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
在這個程序中,我們使用了兩個線程,一個代表快遞員將包裹放到快遞柜里,另一個代表用戶從快遞柜里取出自己的包裹。
通過使用線程同步和wait/notify方法,我們實現了快遞員和用戶之間的交互,讓快遞柜的使用更加順暢。
IO和多線程是Java中非常重要的知識點,它們可以幫助我們處理各種復雜的任務和并發場景。
上一篇docker實例教程
下一篇css 局部超鏈接設置