来电科技-初级Java工程师
forward 和redirect的区别
JAVA常见面试题之Forward和Redirect的区别string和stringbuffer的区别?(+StringBuilder)
1.1 可变与不可变:String一经创建不可再变,Stringbuffer,StringBuilder的对象是变量可更改
1.2 拼接字符串执行效率:jvm会优化string的字符串拼接,所以较少的字符串拼接效率差异不会太大;但相对而言StringBuilder执行更快
1.3 线程安全:StringBuffer线程安全-其几乎所有方法都由synchronized关键字修饰,StringBuilder线程不安全数据库连接池的作用?
3.1 连接资源-重用:数据库连接可重用,避免频繁创建、释放连接引起的大量性能开销
3.2 系统响应-更快:直接利用现有可用连接,避免数据库连接初始化和释放过程的时间开销,缩减系统整体响应时间
3.3 连接管理-统一:超时能强制收回被占用连接。避免常规数据库连接操作中可能出现的资源泄漏写一个单例模式
单线程:
public class Singleton {
private static Singleton singleton = null;
// 私有的构造函数,不让new
private Singleton() {}
public Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
// 多线程
public class Singleton {
private static volatile Singleton singleton = null;
// 私有的构造函数,不让new
private Singleton() {}
public Singleton getSingleton() {
// 已创建就不用执行
if (singleton == null) {
// 获取锁
synchronized(Singleton.class) {
// 其他线程已经获取锁,并创建单例对象
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
- 打印昨天现在的时间,用"年/月/日 时:分:秒"的形式输出
private static Date getPrevDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
return calendar.getTime();
}
private static Date getPrevDay2(Date date) {
long d = date.getTime() - 24 * 60 * 60 * 1000;
return new Date(d);
}
private static void test2() {
Date date = new Date();
SimpleDateFormat ft2 = new SimpleDateFormat ("yyyy/MM/dd hh:mm:ss");
Date date1 = getPrevDay(date);
Date date2 = getPrevDay2(date);
System.out.println("格式化输出3: " + ft2.format(date1));
System.out.println("格式化输出4: " + ft2.format(date2));
}
- 完成一个MyThread类使得下面代码输出100
...
private static x = 0;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread a = new MyThread();
a.start();
}
System.out.println(x);
}
package org.lium.leetcode;
public class MyThread extends Thread {
private static int x = 0;
public MyThread(String name) {
super(name);
}
public void run() {
addOne();
}
private synchronized void addOne() {
System.out.println("线程:" + Thread.currentThread().getName() + "此时X=" + x);
x += 1;
}
public static void main(String[] args) {
System.out.println("初始线程" + Thread.activeCount());
int initialThreadCount = Thread.activeCount();
for (int i = 0; i < 100; i++) {
Thread thread = new MyThread("" + i);
thread.start();
}
for (;;) {
if (Thread.activeCount() == initialThreadCount) {
break;
}
}
System.out.println("线程执行完了:" + x);
}
}