今天小同事找我,說在一個公眾號上看有人分享了幾道阿里面試過程中的筆試題,讓我幫忙捋一捋思路。題目大概是醬紫的:
用兩個執行緒分別列印母音字母和子音字母,列印順序按照26個字母的自然排列順序。
其實,這種問題抓住幾個要點就好了,首先起碼得有兩個執行緒吧:
public class PrintLetterThread implements Runnable{
public static void main(String[] args) throws Throwable {
PrintLetterThread t = new PrintLetterThread();
Thread t1 = new Thread(t,“yuanying”);
Thread t2 = new Thread(t,“fuying”);
t1。start();
t2。start();
}}
簡單建立一個實現Runnable的類,等下就靠它執行任務了。分別給兩個執行緒起一個便於識別的名字,先把執行程式碼寫出來,我們倒著往回寫,什麼叫測試驅動開發。
下面需要把run方法實現一下,兩個執行緒列印26個字母,打完為止,搞一個無限迴圈,然後在打完字母后退出迴圈。
@Override
public void run(){
while (true){
if (ch < 123){
if(isYuanYing(ch) &&
“yuanying”。equals(Thread。currentThread()。getName())) {
System。out。println(Thread。currentThread()。getName() + “ ” + ch); ch++;
}else if(!isYuanYing(ch) {
&&“fuying”。equals(Thread。currentThread()。getName())) {
System。out。println(Thread。currentThread()。getName() + “ ” + ch);
ch++;
}
}else {
break;
}
這裡說明下,我就不寫26個字母了,使用ascii碼值,97~122就是26個字母了,每次列印完把碼值加1,列印下一個字母。
可能有人會在這裡上鎖,上鎖當然是可以搞定的,由於我這裡判斷了執行緒的名字,所以即便是++操作執行緒不安全,兩個執行緒也無法共享同一個ch,什麼叫無鎖併發。
簡單粗暴一些,還是倒著往回寫,現在還差一個判斷母音字母的小方法,這裡新增一下:
char ch = 97;
public boolean isYuanYing(char ch){
if(ch==97||ch==101||ch==105||ch==111||ch==117) {
return true;
}
return false;
}
跟著程式碼思路再遊走一遍,貌似沒啥問題,run一下看看結果:
遇到問題慢慢分析一波,解題方法千萬條,簡單粗暴第一條。因為這裡run方法指定了只能由母音執行緒列印母音字母,子音執行緒列印子音字母,所以兩個執行緒不用考慮先後啟動順序。【完】