來電科技-初級Java工程師
forward 和redirect的區(qū)別
JAVA常見面試題之Forward和Redirect的區(qū)別string和stringbuffer的區(qū)別殴玛?(+StringBuilder)
1.1 可變與不可變:String一經(jīng)創(chuàng)建不可再變,Stringbuffer,StringBuilder的對象是變量可更改
1.2 拼接字符串執(zhí)行效率:jvm會優(yōu)化string的字符串拼接,所以較少的字符串拼接效率差異不會太大;但相對而言StringBuilder執(zhí)行更快
1.3 線程安全:StringBuffer線程安全-其幾乎所有方法都由synchronized關(guān)鍵字修飾萎庭,StringBuilder線程不安全數(shù)據(jù)庫連接池的作用早敬?
3.1 連接資源-重用:數(shù)據(jù)庫連接可重用蜗巧,避免頻繁創(chuàng)建、釋放連接引起的大量性能開銷
3.2 系統(tǒng)響應(yīng)-更快:直接利用現(xiàn)有可用連接牙捉,避免數(shù)據(jù)庫連接初始化和釋放過程的時間開銷,縮減系統(tǒng)整體響應(yīng)時間
3.3 連接管理-統(tǒng)一:超時能強(qiáng)制收回被占用連接敬飒。避免常規(guī)數(shù)據(jù)庫連接操作中可能出現(xiàn)的資源泄漏寫一個單例模式
單線程:
public class Singleton {
private static Singleton singleton = null;
// 私有的構(gòu)造函數(shù)邪铲,不讓new
private Singleton() {}
public Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
// 多線程
public class Singleton {
private static volatile Singleton singleton = null;
// 私有的構(gòu)造函數(shù),不讓new
private Singleton() {}
public Singleton getSingleton() {
// 已創(chuàng)建就不用執(zhí)行
if (singleton == null) {
// 獲取鎖
synchronized(Singleton.class) {
// 其他線程已經(jīng)獲取鎖无拗,并創(chuàng)建單例對象
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
- 打印昨天現(xiàn)在的時間带到,用"年/月/日 時:分:秒"的形式輸出
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("線程執(zhí)行完了:" + x);
}
}