import java.util.ArrayList; import static java.lang.Thread.sleep; import…
- User
import java.util.ArrayList; import static java.lang.Thread.sleep; import java.util.Scanner; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException;
class Router {
codepublic boolean[] connected; public int maxDevices; public int currentConnectedDevices; public Semaphore semaphore; Router(int maxDevices) { this.maxDevices = maxDevices; semaphore = new Semaphore(maxDevices); connected = new boolean[maxDevices]; } public synchronized int connect(Device device) throws InterruptedException { for (int i = 0; i < maxDevices; i++) { if (!connected[i]) { currentConnectedDevices++; device.setConnectionID(i + 1); connected[i] = true; sleep(50); break; } } return device.getConnectionID(); } public synchronized void disconnect(Device device) { currentConnectedDevices--; connected[device.getConnectionID() - 1] = false; notify(); String s ="Connection " + device.getConnectionID() + ": " + device.getName2() + " Logged out"; Network.write(s); //System.out.println("Connection " + device.getConnectionID() + ": " + device.getName2() + " Logged out"); } public synchronized void deviceArrived(Device device) { // System.out.println( device.getName2() +" (" + device.getType() + ")" +" // arrived"); }}
class Semaphore {
code - Assistant
هذا هو الشرح لكل سطر من الشيفرة:
-
import java.util.ArrayList;: استيراد الفئة ArrayList من حزمة java.util.
-
- User
اشرح صح اشرح ال synchronization واشرح الموجود داخل class device
- Assistant
التزامن (Synchronization):
التزامن في Java يتم استخدامه لضمان أن أجزاء معينة من الشيفرة لا يتم تنفيذها بشكل متزامن من قبل عدة خيوط في نفس الوقت. يتم استخدامه للتحكم في تنفيذ الشيفرة بين الخيوط المختلفة لضمان تجنب حدوث أخطاء نتيجة تعارض البيانات.