admin 1 rok temu
rodzic
commit
3d9d7f2913

+ 43 - 0
codingGuidelines/src/CheckLock.java

@@ -0,0 +1,43 @@
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class CheckLock {
+
+    private static Lock lock = new ReentrantLock();
+
+    public static void main(String[] args) {
+        Thread thread1 = new Thread(new Worker());
+        Thread thread2 = new Thread(new Worker());
+
+        // Start the threads
+        thread1.start();
+        thread2.start();
+    }
+
+    static class Worker implements Runnable {
+        @Override
+        public void run() {
+            // Acquire the lock
+            lock.lock();
+
+            try {
+                System.out.println(Thread.currentThread().getName() + " acquired the lock.");
+
+                // Perform some work
+                for (int i = 0; i < 5; i++) {
+                    System.out.println(Thread.currentThread().getName() + " is working.");
+                    try {
+                        Thread.sleep(1000);
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                }
+
+            } finally {
+                // Release the lock
+                lock.unlock();
+                System.out.println(Thread.currentThread().getName() + " released the lock.");
+            }
+        }
+    }
+}

+ 42 - 0
codingGuidelines/src/CloneObject.java

@@ -0,0 +1,42 @@
+
+class Num implements Cloneable {
+    double num = 10.0;
+
+    @Override
+    protected Object clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+}
+
+public class CloneObject implements Cloneable {
+
+    Num number;
+
+    public CloneObject() {
+        this.number = new Num();
+    }
+
+    public static void main(String[] args) throws CloneNotSupportedException {
+        CloneObject cloneObject = new CloneObject();
+        CloneObject cloned = (CloneObject) cloneObject.clone();
+        System.out.println(cloned.getNumber().num); // 10.0
+        System.out.println(cloneObject.getNumber().num); // 10.0
+        cloned.number.num = 20.0;
+        System.out.println(cloned.number.num); // 20.0
+        System.out.println(cloneObject.number.num); // 深:10.0 浅: 20.0
+    }
+
+    public Num getNumber() {
+        return number;
+    }
+
+    public void setNumber(Num number) {
+        this.number = number;
+    }
+
+    public Object clone() throws CloneNotSupportedException {
+        CloneObject cloneObject = (CloneObject) super.clone();
+        cloneObject.number = (Num) this.number.clone(); // 加上这行会变为深拷贝
+        return cloneObject;
+    }
+}

+ 48 - 0
codingGuidelines/src/CollectorsToMap.java

@@ -0,0 +1,48 @@
+import javafx.util.Pair;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static javafx.scene.input.KeyCode.T;
+
+public class CollectorsToMap {
+    public static void main(String[] args) {
+        List<Pair<String, Double>> pairArrayList = new ArrayList<>(3);
+        pairArrayList.add(new Pair<>("version", 12.10));
+        pairArrayList.add(new Pair<>("version", 12.19));
+        pairArrayList.add(new Pair<>("version", 6.28));
+        // 生成的 map 集合中只有一个键值对:{version=6.28}
+        Map<String, Double> map = pairArrayList.stream().collect(Collectors.toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2));
+        System.out.println(map);
+
+        // 不能这么写:
+        String[] departments = new String[]{"RDC", "RDC", "KKB"};
+        // 抛出 IllegalStateException 异常
+        try {
+            Map<Integer, String> map1 = Arrays.stream(departments).collect(Collectors.toMap(String::hashCode, str -> str));
+            System.out.println(map1);
+        } catch (IllegalStateException e) {
+            e.printStackTrace(); // java.lang.IllegalStateException: Duplicate key RDC
+        }
+
+        // -------------------------------------------------------------------------------------------------------------
+
+        String[] departments1 = new String[]{null, "RDC", "KKB"};
+        // 抛出 IllegalStateException 异常
+        try {
+            Map<Integer, String> map1 = Arrays.stream(departments1).collect(Collectors.toMap(String::hashCode, str -> str));
+            System.out.println(map1);
+        } catch (Exception e) {
+            e.printStackTrace(); // java.lang.NullPointerException
+        }
+
+        // 可以写为:
+        Map<Integer, String> map2 = Arrays.stream(departments1)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toMap(
+                        key -> key.hashCode(),
+                        value -> Optional.ofNullable(value).orElse("null")
+                ));
+        System.out.println(map2);
+    }
+}

+ 41 - 0
codingGuidelines/src/EqualsHashCode.java

@@ -0,0 +1,41 @@
+import java.util.HashSet;
+import java.util.Objects;
+
+class EqualsHashCode {
+    private String name;
+    private int age;
+
+    public EqualsHashCode(String name, int age) {
+        this.name = name;
+        this.age = age;
+    }
+
+    // 如果没有这个重写,最后personSet中会有两个对象
+    public int hashCode() {
+        return Objects.hash(name, age);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == this) {
+            return true;
+        }
+
+        if (obj == null || obj.getClass() != this.getClass()) {
+            return false;
+        }
+
+        EqualsHashCode other = (EqualsHashCode) obj;
+        return this.name.equals(other.name) && this.age == other.age;
+    }
+
+    public static void main(String[] args) {
+        EqualsHashCode person1 = new EqualsHashCode("John", 25);
+        EqualsHashCode person2 = new EqualsHashCode("John", 25);
+
+        HashSet<EqualsHashCode> personSet = new HashSet<>();
+        personSet.add(person1);
+        personSet.add(person2);
+        System.out.println(personSet);
+    }
+}

+ 13 - 0
codingGuidelines/src/FloatEquals.java

@@ -0,0 +1,13 @@
+import javax.xml.soap.SOAPPart;
+
+public class FloatEquals {
+    static float a = 1.0F - 0.9F;
+    static float b = 0.9F - 0.8F;
+
+    public static void main(String[] args) {
+        System.out.println(a);
+        System.out.println(b);
+        System.out.println(a==b);
+        System.out.println(Float.valueOf(a).equals(Float.valueOf(b)));
+    }
+}

+ 40 - 0
codingGuidelines/src/ForLoopAddRemove.java

@@ -0,0 +1,40 @@
+import java.util.ArrayList;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.List;
+
+public class ForLoopAddRemove {
+
+    public static void main(String[] args) {
+        List<Integer> numbers = new ArrayList<>();
+        for (int i = 0; i < 10; i++) {
+            numbers.add(i);
+        }
+
+        // Create a thread to remove elements using foreach
+        Thread thread1 = new Thread(() -> {
+            try {
+                for (Integer number : numbers) {
+                    System.out.println("Removing element using foreach: " + number);
+                    numbers.remove(number); // ConcurrentModificationException will occur
+                }
+            } catch (ConcurrentModificationException e) {
+                System.out.println("Caught ConcurrentModificationException when modifying list using foreach.");
+            }
+        });
+
+        // Create a thread to remove elements using iterator
+        Thread thread2 = new Thread(() -> {
+            Iterator<Integer> iterator = numbers.iterator();
+            while (iterator.hasNext()) {
+                Integer number = iterator.next();
+                System.out.println("Removing element using iterator: " + number);
+                iterator.remove(); // Works fine with iterator
+            }
+        });
+
+        // Start the threads
+        thread1.start();
+        thread2.start();
+    }
+}

+ 16 - 0
codingGuidelines/src/ForLoopString.java

@@ -0,0 +1,16 @@
+
+public class ForLoopString {
+    public static void main(String[] args) {
+        System.out.println(System.currentTimeMillis());
+        String str = "start" ;
+        for (int i = 0; i < 10000; i++) {
+            str = str + "hello";
+        }
+        System.out.println(System.currentTimeMillis());
+        StringBuilder str1 = new StringBuilder("start");
+        for (int i = 0; i < 10000; i++) {
+            str1 = str1.append("hello");
+        }
+        System.out.println(System.currentTimeMillis());
+    }
+}

+ 41 - 0
synchronized/src/SynchronizedTest.java

@@ -0,0 +1,41 @@
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class SynchronizedTest implements Runnable{
+    private static int i = 0;
+
+    public synchronized void getI() throws InterruptedException {
+        if (i % 1000000 == 0) {
+
+            System.out.println(i+"--"+Thread.currentThread());
+//            Thread.sleep(5000);
+        }
+    }
+
+    public synchronized void increase() throws InterruptedException {
+        i++;
+        getI();
+    }
+
+    @Override
+    public void run() {
+        for (int j = 0; j < 1000000; j++) {
+            try {
+                increase();
+            } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        System.out.println(i+"--"+Thread.currentThread());
+    }
+
+    public static void main(String[] args) {
+        ExecutorService executorService = Executors.newCachedThreadPool();
+        SynchronizedTest synchronizedTest = new SynchronizedTest();
+        SynchronizedTest synchronizedTest1 = new SynchronizedTest();
+        executorService.execute(synchronizedTest);
+        executorService.execute(synchronizedTest1);
+        executorService.shutdown();
+    }
+}