jdk1.5以後有了java.util.concurrent包
裡面對同步提供了相當多的支援
例如lock atomic以及一些可同步操作的容器
下面給出一個常見的多線程面試題及其對應實現
有三個線程ID分別是A、B、C,請有多線編程實現,在螢幕上迴圈列印10次ABCABC
採用AtomicInteger來實現這個,
不多說了,上代碼,還是相當簡單易懂的
可以對concurrent包見一斑。
1. import java.util.concurrent.atomic.AtomicInteger; 2. 3. public class Print extends Thread{ 4. //專門為同步用的 用integer不行,每次都會建立的 5. private AtomicInteger synObj; 6. private int count; 7. private String s; 8. private int flag; 9. private int total = 0; 10. 11. public Print(int count,AtomicInteger atomicInteger,String s,int flag) { 12. this.count = count; 13. this.synObj = atomicInteger; 14. this.s = s; 15. this.flag = flag; 16. } 17. public void run() { 18. while(true) { 19. synchronized(synObj) { 20. if(synObj.intValue()%3 == flag) { 21. total++; 22. synObj.set(synObj.intValue()+1); 23. System.out.println(s); 24. synObj.notifyAll(); 25. if(total == count) { 26. break; 27. } 28. }else { 29. try{ 30. synObj.wait(); 31. }catch(Exception e){ 32. e.printStackTrace(); 33. } 34. } 35. } 36. } 37. } 38. public static void main(String[]args) throws Exception { 39. AtomicInteger synObj = new AtomicInteger(0); 40. Print a = new Print(10,synObj,"A",0); 41. Print b = new Print(10,synObj,"B",1); 42. Print c = new Print(10,synObj,"C",2); 43. a.start(); 44. b.start(); 45. c.start(); 46. } 47. }