public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// 私有构造函数,防止外部实例化对象
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
// 其他业务逻辑代码...
}
public class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // 输出结果为 true,说明获取的实例是同一个对象
}
}Java多线程编程中的同步问题解决
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
Thread thread1 = new Thread(() -> {
for (int i = 0; i< 1000; i++) {
example.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i< 1000; i++) {
example.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + example.count); // 输出结果为 2000,说明同步成功
}
}Java异常处理机制及最佳实践
public class ExceptionHandling {
public static void main(String[] args) {
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = divide(num1, num2);
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please provide two numbers as input.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
public static int divide(int num1, int num2) {
return num1 / num2;
}
}Java常用数据结构之链表的实现
public class ListNode {
private int val;
private ListNode next;
public ListNode(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
public class LinkedList {
private ListNode head;
public LinkedList() {
head = null;
}
public void insert(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode temp = head;
while (temp.getNext() != null) {
temp = temp.getNext();
}
temp.setNext(newNode);
}
}
public void display() {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.getVal() + " ");
temp = temp.getNext();
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.display(); // 输出结果为 1 2 3
}
}