三个线程循环按顺序进行打印

本文探讨了如何使用三个线程按顺序打印字符串'ABC'各10次,以及如何顺序打印数字1到75,每个线程负责连续5个数字。解决方案涉及使用同步代码块、AtomicInteger类以及线程间的协调唤醒机制。

一、三个线程顺序打印ABC10次

解决方案一:适用三个标志来标识哪个线程应该等待,分别在三个线程中使用同步代码块。

public class solution{
	private static boolean flag1=true;
	private static boolean flag2=false;
	private static boolean flag3=false;
	
	public static void main(String[] args){
		final solution o=new solution();
		Thread t1=new Thread(new Runnable(){
			public void run(){
				for(int i=0;i<10;i++){
					while(true){
						synchronized(o){
							if(!flag1){
								try {
									o.wait();
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}else{
								System.out.println(Thread.currentThread().getName());
								flag1=false;
								flag2=true;
								flag3=false;
								o.notifyAll();
								break;
							}
						}
					}
				}
			}
		},"A");
		
		Thread t2=new Thread(new Runnable(){
			public void run(){
				for(int i=0;i<10;i++){
					while(true){
						synchronized(o){
							if(!flag2){
								try {
									o.wait();
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}else{
								System.out.println(Thread.currentThread().getName());
								flag1=false;
								flag2=false;
								flag3=true;
								o.notifyAll();
								break;
							}
						}
					}
				}
			}
			
		},"B");
		
		Thread t3=new Thread(new Runnable(){
			public void run(){
				for(int i=0;i<10;i++){
					while(true){
						synchronized(o){
						if(!flag3){
							try {
								o.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}else{
							System.out.println(Thread.currentThread().getName());
							flag1=true;
							flag2=false;
							flag3=false;
							o.notifyAll();
							break;
						}
					}
				  }
				}
			}
		},"C");
		
		t1.start();
		t2.start();
		t3.start();
	}
}

解决方案二:使用原子类 AtomicInteger类 ,AtomicInteger类线程安全,适合在高并发中当计数器.

class threadTest extends Thread{
	private AtomicInteger synobj;
	private String name;//打印的字母
	private int flag;//线程标识
	
	private int count=0;//统计打印的次数。
	
	public threadTest(AtomicInteger synobj,String name,int flag){
		this.synobj=synobj;
		this.name=name;
		this.flag=flag;
	}
	
	public void run(){
			while(true){
				synchronized(synobj){
					if(synobj.get()%3==flag){
						synobj.set(synobj.get()+1);
						System.out.println(name);
						count++;
						synobj.notifyAll();
						if(count==10){
							break;
						}else{
							try {
								synobj.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
				}
			}
		}
	}
	
}

public class solution{
	public static void main(String[] args){
		AtomicInteger synobj=new AtomicInteger(0);
		
		threadTest t1=new threadTest(synobj,"A",0);
		threadTest t2=new threadTest(synobj,"B",1);
		threadTest t3=new threadTest(synobj,"C",2);
		
		t1.start();
		t2.start();
		t3.start();
	}
}

二、要求用三个线程,按顺序打印1,2,3,4,5.... 71,72,73,74, 75.

线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到线程3打印到75。

解决思路:创建一个线程对应的类型,三个线程分开处理。分别调用三个不同的线程,循环打印5个数字,打印完以后唤醒其他休眠的线程,然后自己休眠。

public class sortedAlgorithm {
	
	static int type = 1;//线程对应的类型,三个线程分开处理
	static int number = 1;//打印数字的起始
	
	public static void main(String[] args) {
		new Thread("第一个线程:") { // 创建一个线程,命名为第一个线程
			public void run() {
				try {
					synchronized (sortedAlgorithm.class) {
						while (number <= 75) {					
							if (type == 1) {//当type的值为1的时候,由第一个线程来打印
								for (int i = 0; i < 5; i++) {
									System.out.println(Thread.currentThread().getName() + ":" + number++);
								}	
								type = 2;//修改类型值
								sortedAlgorithm.class.notifyAll();//唤醒其他进入休眠的线程
							} else {
								sortedAlgorithm.class.wait();
							}
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
		
		new Thread("第二个线程:") { // 创建二个线程,命名为第二个线程
			public void run() {
				try {
					synchronized (sortedAlgorithm.class) {
						while (number <= 75) {
							if (type == 2) {
								for (int i = 0; i < 5; i++) {
									System.out.println(Thread.currentThread().getName() + ":" + number++);
								}
								type = 3;
								sortedAlgorithm.class.notifyAll();
							} else {
								sortedAlgorithm.class.wait();
							}
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
		new Thread("第三个线程:") { // 创建三个线程,命名为第三个线程
			public void run() {
				try {
					synchronized (sortedAlgorithm.class) {
						while (number <= 75) {
							if (type == 3) {
								for (int i = 0; i < 5; i++) {
									System.out.println(Thread.currentThread().getName() + ":" + number++);
								}
								type = 1;
								sortedAlgorithm.class.notifyAll();
								if (number < 76)
								sortedAlgorithm.class.wait();
							} else {
								sortedAlgorithm.class.wait();
							}
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}
}

 

为了实现三个线程循环打印ABC,可以使用Synchronized同步方法和Object的wait()和notify()方法。首先,创建三个线程A、B、C,并设置它们的打印次数为10。然后,通过使用三个对象锁a、b、c来控制线程的执行顺序。A线程首先获得c对象锁,打印A后释放c对象锁,并通过notify()方法唤醒B线程。B线程等待a对象锁,获取到a对象锁后打印B,并释放a对象锁,然后通过notify()方法唤醒C线程。C线程等待b对象锁,获取到b对象锁后打印C,并释放b对象锁,并通过notify()方法唤醒A线程。这样就实现了三个线程循环打印ABC的需求。 以下是一个示例代码: ```java class PrintThread implements Runnable { private static final Object a = new Object(); private static final Object b = new Object(); private static final Object c = new Object(); private String name; public PrintThread(String name) { this.name = name; } @Override public void run() { for (int i = 0; i < 10; i++) { synchronized (name) { try { switch (name) { case "A": synchronized (c) { System.out.print("A"); c.notify(); } name.wait(); break; case "B": synchronized (a) { System.out.print("B"); a.notify(); } name.wait(); break; case "C": synchronized (b) { System.out.print("C"); b.notify(); } name.wait(); break; } } catch (InterruptedException e) { e.printStackTrace(); } } } } } public class Main { public static void main(String[] args) { Thread threadA = new Thread(new PrintThread("A")); Thread threadB = new Thread(new PrintThread("B")); Thread threadC = new Thread(new PrintThread("C")); threadA.start(); threadB.start(); threadC.start(); } } ``` 通过以上代码,三个线程将按照ABCABCABC的顺序循环打印10次。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [多线程交替打印ABC的多种实现方法](https://blog.youkuaiyun.com/xiaokang123456kao/article/details/77331878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [三个线程轮流打印ABC](https://blog.youkuaiyun.com/yu1336199790/article/details/118725454)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值