2,shell 第二部分
阿新 • • 發佈:2020-08-18
1、單例模式,手寫雙重檢驗單例模式 懶漢式,DCL(8)
餓漢式:
public class Singleton{
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getSingleton(){
return singleton;
}
}
懶漢式(執行緒不安全):
public class Singleton{
private static Singleton singleton = null ;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
雙重校驗單例模式(DCL):
public class Singleton{
private volatile static Singleton singleton;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
//類物件加鎖
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
2、rand4生成rand6
- 給定一個 0-4隨機數生成器 如何生成0-6隨機數
public class Frequency {
public static int rand7(){
while(true){
int num=5*rand5()+rand5();//0-24
if(num<21)
return num % 7;
}
}
}
//變形:如果用0-6隨機生成器生成0-9隨機數
public class Frequency {
public static int rand10(){
while(true){
int num=7*rand7()+rand7();
if(num<41)
//排除41-48,因為他們不能生成9,會造成各個數字出現的概率不同
return num % 10;
}
}
}
3、最長不含重複字元的子字串(劍指offer48題)
請從字串中找出一個最長的不包含重複字元的子字串,計算該最長子字串的長度。 示例1: 輸入: "abcabcbb" 輸出: 3 解釋: 因為無重複字元的最長子串是 "abc",所以其長度為 3。雙指標+雜湊表 時間複雜度O(N) 空間複雜度O(1):字元的 ASCII 碼範圍為 0 ~ 127 ,
雜湊表 dicdic 最多使用 O(128) = O(1)大小的額外空間。
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> dic = new HashMap<>();
int i = -1, res = 0;
for(int j = 0; j < s.length(); j++) {
if(dic.containsKey(s.charAt(j)))
i = Math.max(i, dic.get(s.charAt(j))); // 更新左指標 i
dic.put(s.charAt(j), j); // 雜湊表記錄
res = Math.max(res, j - i); // 更新結果
}
return res;
}
}
4、三個執行緒迴圈列印ABC
本題有多種方法實現,如wait,notify,synchronized等,這裡給出基於Lock的實現//使用Lock
public class ABCPrint{
private static int state = 0;
public static void main(String[] args) {
final Lock lock = new ReentrantLock();
Thread A = new Thread(new Runnable() { <a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 0) {
System.out.print("A");
state++;
}
} finally {
lock.unlock();
}
}
}
});
Thread B = new Thread(new Runnable() { </a><a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 1) {
System.out.print("B");
state++;
}
} finally {
lock.unlock();
}
}
}
});
Thread C = new Thread(new Runnable() { </a><a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 2) {
System.out.println("C");
state++;
}
} finally {
lock.unlock();
}
}
}
});
A.start();
B.start();
C.start();
}
}</a>
2、rand4生成rand6
[2,Rand4 shēngchéng rand6]
2, rand4 generated rand6