使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束


简要分析:

要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中。同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来输出对应的信息。

package com.test;

public class PrintOneTwoThree {
	public static void main(String[] args) {
		Print p1 = new Print(0);
		Print p2 = new Print(1);
		Print p3 = new Print(2);

		new Thread(p1, "p1").start();
		new Thread(p2, "p2").start();
		new Thread(p3, "p3").start();

		while (Thread.activeCount() > 1)
			;
		System.out.println("Done!");
	}
}

class Print implements Runnable {
	private static int state = 0;
	private int id;
	private static Object lock = new Object();

	public Print(int id) {
		this.id = id;
	}

	@Override
	public void run() {
		synchronized (lock) {
			while (state < 30) {
				if (state % 3 == id) {
					switch (id) {
					case 0:
						System.out.println("["
								+ Thread.currentThread().getName() + "]" + "A");
						break;

					case 1:
						System.out.println("["
								+ Thread.currentThread().getName() + "]" + "B");
						break;
						
					case 2:
						System.out.println("["
								+ Thread.currentThread().getName() + "]" + "C");
						break;

					default:
						break;
					}
					state++;
					lock.notifyAll();
				} else {
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM