Python 官方文档:入门教程 => 点击学习
目录1. 使用try-with-resources简化文件读取操作:2. 使用Lambda表达式简化集合操作:3. 使用StringBuilder类拼接字符串:4. 使用静态导入简化
修改前:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// ...
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改后:
try (FileInputStream fis = new FileInputStream("file.txt")) {
// ...
} catch (IOException e) {
e.printStackTrace();
}
修改前:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
修改后:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
修改前:
String s = "";
for (int i = 0; i < 10; i++) {
s += i;
}
修改后:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
String s = sb.toString();
修改前:
System.out.println(Math.sqrt(2));
修改后:
import static java.lang.Math.sqrt;
System.out.println(sqrt(2));
修改前:
if (x < 0) {
throw new IllegalArgumentException("x must be non-negative");
}
修改后:
assert x >= 0 : "x must be non-negative";
修改前:
String s = null;
if (s != null) {
System.out.println(s.length());
}
修改后:
Optional<String> optional = Optional.ofNullable(null);
optional.ifPresent(s -> System.out.println(s.length()));
修改前:
public static final int STATUS_NEW = 0;
public static final int STATUS_PROCESSING = 1;
public static final int STATUS_COMPLETED = 2;
修改后:
public enum Status {
NEW,
PROCESSING,
COMPLETED
}
修改前:
try {
// ...
} catch (Exception e) {
e.printStackTrace();
}
修改后:
try {
// ...
} catch (MyCustomException e) {
e.printStackTrace();
}
修改前:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = new ArrayList<>();
for (int number : numbers) {
if (number % 2 == 0) {
evenNumbers.add(number);
}
}
修改后:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
修改前:
public class MyRunnable implements Runnable {
private int count = 0;
public void run() {
for (int i = 0; i < 100000; i++) {
count++;
}
System.out.println(count);
}
}
修改后:
public class MyRunnable implements Runnable {
private ThreadLocal<Integer> count = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public void run() {
for (int i = 0; i < 100000; i++) {
count.set(count.get() + 1);
}
System.out.println(count.get());
}
}
在多线程环境下,使用普通的成员变量会导致线程安全问题,而使用ThreadLocal可以确保每个线程访问的变量是独立的,避免了线程安全问题。在上面的示例中,使用ThreadLocal确保了每个线程访问的count变量是独立的,从而避免了线程安全问题。
以上就是从try-with-resources到ThreadLocal,优化你的代码编写方式的详细内容,更多关于try-with-resources ThreadLocal优化代码的资料请关注编程网其它相关文章!
--结束END--
本文标题: 从try-with-resources到ThreadLocal,优化你的代码编写方式
本文链接: https://lsjlt.com/news/208908.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0