Java多线程编程--(5)Java多线程互斥小例子

前几篇写了Java从出生就支持的多线程的一些技术,打算往后就写一下Java 5.0新推出的多线程编程相关的包和类,今天就写一个小例子作为老技术部分的小结吧。上题:

“A线程循环n次输出语句,然后B线程循环m次输出语句,然后再由A线程循环n次输出语句,B循环m次输出语句.....如此反复50次即可。”

[java] view plain copy
 
  1. package cn.test;  
  2.   
  3. public class ThreadExclusiveTest {  
  4.   
  5.     public static void main(String[] args) {  
  6.           
  7.         final ThreadTask tt = new ThreadTask();  
  8.         new Thread(new Runnable(){  
  9.   
  10.             @Override  
  11.             public void run() {  
  12.                   
  13.                 int i = 0;  
  14.                 while(i<50){  
  15.                       
  16.                     tt.firstTask(100, 0, i+1);  
  17.                     i++;  
  18.                 }  
  19.             }  
  20.               
  21.         }, "B线程").start();  
  22.           
  23.         new Thread(new Runnable(){  
  24.   
  25.             @Override  
  26.             public void run() {  
  27.                   
  28.                 int i = 0;  
  29.                 while(i<50){  
  30.                       
  31.                     tt.firstTask(10, 1, i+1);  
  32.                     i++;  
  33.                 }  
  34.             }  
  35.               
  36.         }, "A线程").start();  
  37.     }  
  38.   
  39. }  
  40.   
  41. /** 
  42.  * 线程执行任务类,其中封装了线程需要执行的所有任务,各个任务之间的互斥在该类中进行处理! 
  43.  */  
  44. class ThreadTask {  
  45.       
  46.     private int controller = 0;  
  47.       
  48.     /** 
  49.      * 第一任务:线程的具体执行逻辑。 
  50.      * @param executeTimes 输出次数 
  51.      * @param ctrlWaitValue 线程等待的控制值 
  52.      * @param executeTimes 
  53.      */  
  54.     public synchronized void firstTask(int executeTimes, int ctrlWaitValue, int loopTime){  
  55.           
  56.         while(controller%2 == ctrlWaitValue){  
  57.               
  58.             try {  
  59.                 wait();  
  60.             } catch (InterruptedException e) {  
  61.                 e.printStackTrace();  
  62.             }  
  63.         }  
  64.         for(int i=0; i<executeTimes; i++){  
  65.               
  66.             System.out.println(Thread.currentThread().getName() + " 开始第 " + i + " 次执行!第  " +loopTime+" 主循环!");  
  67.         }  
  68.         controller++;  
  69.         notifyAll();  
  70.     }  
  71. }  


上例中,将题目中的任务封装在类ThreadTask的方法firstTask中,测试类中,A线程先循环10次,B线程循环50次,然后A在循环10次,依次进行50次,结束。

posted @ 2016-12-02 15:24  天涯海角路  阅读(181)  评论(0)    收藏  举报