上个星期我到诚迈科技参加面试.面试完毕后面试官让我把笔试卷上的一道多线程题在计算机上编程实现.题目如下:
四个线程a,b,c,d. 线程a,b对变量i加一. 线程c,d对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0, 打印结果0 1 2 1 0 1 2 1 0 1 2...
这道题还是有一定的难度的. 因为要求顺序执行. 不能简单用同步.
经考虑,我决定用一个队列来对四个线程顺序调度.代码如下:
- 1.package org.jenfer.struts2demo.web.struts2.action;
- 2.
- 3.import java.util.concurrent.BlockingQueue;
- 4.import java.util.concurrent.ExecutorService;
- 5.import java.util.concurrent.Executors;
- 6.import java.util.concurrent.LinkedBlockingQueue;
- 7.
- 8./**
- 9. * 四个线程a,b,c,d. 线程a,b对变量i加一.
- 10. * 线程c,d对变量i减去一.四个线程顺序执行,
- 11. * 每个线程每次只执行一次.i的初始值为0,
- 12. * 打印结果0 1 2 1 0 1 2 1 0 1 2...
- 13. *
- 14. * @author 武汉科技大学08级研究生周剑华
- 15. *
- 16. */
- 17.public class MultiThreadTest {
- 18. //variable i
- 19. private int i=0;
- 20. //queue to control thread invoke
- 21. private BlockingQueue<Integer> queue=new LinkedBlockingQueue<Integer>();
- 22.
- 23. public MultiThreadTest() {
- 24. queue.offer(1);
- 25. queue.offer(2);
- 26. queue.offer(3);
- 27. queue.offer(4);
- 28. }
- 29.
- 30. public synchronized void inc(int con) throws InterruptedException{
- 31. while(true){
- 32. int c=queue.peek();
- 33. if(c==con){
- 34. break;
- 35. }else{
- 36. notifyAll();
- 37. wait();
- 38. }
- 39. }
- 40.
- 41. queue.offer(queue.take());
- 42.
- 43. i++;
- 44. System.out.println(Thread.currentThread().getName()+",i="+i);
- 45. }
- 46.
- 47. public synchronized void dec(int con) throws InterruptedException{
- 48. while(true){
- 49. int c=queue.peek();
- 50. if(c==con){
- 51. break;
- 52. }else{
- 53. notifyAll();
- 54. wait();
- 55. }
- 56. }
- 57.
- 58. queue.offer(queue.take());
- 59. i--;
- 60. System.out.println(Thread.currentThread().getName()+",i="+i);
- 61. }
- 62.
- 63. private class IncThread implements Runnable{
- 64. private int condition;
- 65. public IncThread(int condition) {
- 66. this.condition=condition;
- 67. }
- 68. public void run() {
- 69. while(true){
- 70. try {
- 71. inc(condition);
- 72. } catch (InterruptedException e) {
- 73. System.err.println(Thread.currentThread().getName()+" exit now");
- 74. break;
- 75. }
- 76. }
- 77. }
- 78. }
- 79.
- 80. private class DecThread implements Runnable{
- 81. private int condition;
- 82. public DecThread(int condition) {
- 83. this.condition=condition;
- 84. }
- 85. public void run() {
- 86. while(true){
- 87. try {
- 88. dec(condition);
- 89. } catch (InterruptedException e) {
- 90. System.err.println(Thread.currentThread().getName()+" exit now");
- 91. break;
- 92. }
- 93. }
- 94. }
- 95. }
- 96.
- 97. public static void main(String[] args) {
- 98. MultiThreadTest test=new MultiThreadTest();
- 99. ExecutorService exec=Executors.newFixedThreadPool(4);
- 100. exec.submit(test.new IncThread(1));
- 101. exec.submit(test.new IncThread(2));
- 102. exec.submit(test.new DecThread(3));
- 103. exec.submit(test.new DecThread(4));
- 104.
- 105. exec.shutdown();
- 106. }
- 107.}