前几篇写了Java从出生就支持的多线程的一些技术,打算往后就写一下Java 5.0新推出的多线程编程相关的包和类,今天就写一个小例子作为老技术部分的小结吧。上题:
“A线程循环n次输出语句,然后B线程循环m次输出语句,然后再由A线程循环n次输出语句,B循环m次输出语句.....如此反复50次即可。”
- package cn.test;
- public class ThreadExclusiveTest {
- public static void main(String[] args) {
- final ThreadTask tt = new ThreadTask();
- new Thread(new Runnable(){
- @Override
- public void run() {
- int i = 0;
- while(i<50){
- tt.firstTask(100, 0, i+1);
- i++;
- }
- }
- }, "B线程").start();
- new Thread(new Runnable(){
- @Override
- public void run() {
- int i = 0;
- while(i<50){
- tt.firstTask(10, 1, i+1);
- i++;
- }
- }
- }, "A线程").start();
- }
- }
- /**
- * 线程执行任务类,其中封装了线程需要执行的所有任务,各个任务之间的互斥在该类中进行处理!
- */
- class ThreadTask {
- private int controller = 0;
- /**
- * 第一任务:线程的具体执行逻辑。
- * @param executeTimes 输出次数
- * @param ctrlWaitValue 线程等待的控制值
- * @param executeTimes
- */
- public synchronized void firstTask(int executeTimes, int ctrlWaitValue, int loopTime){
- while(controller%2 == ctrlWaitValue){
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for(int i=0; i<executeTimes; i++){
- System.out.println(Thread.currentThread().getName() + " 开始第 " + i + " 次执行!第 " +loopTime+" 主循环!");
- }
- controller++;
- notifyAll();
- }
- }
上例中,将题目中的任务封装在类ThreadTask的方法firstTask中,测试类中,A线程先循环10次,B线程循环50次,然后A在循环10次,依次进行50次,结束。