欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三个线程循环切换

程序员文章站 2022-04-17 20:09:18
...
package com.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest3 {
	public static void main(String[] args) {
		
		final Business business=new Business();

		
		//线程三
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 5; i++) {
					try {
						business.sub3(i);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		//线程二
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 5; i++) {
					try {
						business.sub2(i);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		

		
		//main方法本身是个线程,即线程二运行代码直接放到main方法中
		for (int i = 0; i < 5; i++) {
			try {
				business.main(i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	
	static class Business{
		Lock lock=new ReentrantLock();
		Condition condition1=lock.newCondition();
		Condition condition2=lock.newCondition();
		Condition condition3=lock.newCondition();
		
		private int isSub=1;//当前运行的方法是main();
		
		//线程三
		public  void sub3(int i) throws InterruptedException {
			lock.lock();
			while (isSub!=3) {
				condition3.await();
			}
			for (int j = 0; j < 10; j++) {
				System.out.println("sub3 thread sequence is "+j+" and loop is "+i);
			}
			isSub = 1;
			condition1.signal();
			lock.unlock();
		}
		
		//线程二
		public  void sub2(int i) throws InterruptedException {
			lock.lock();
			while (isSub!=2) {
				condition2.await();
			}
			for (int j = 0; j < 10; j++) {
				System.out.println("sub2 thread sequence is "+j+" and loop is "+i);
			}
			isSub = 3;
			condition3.signal();
			lock.unlock();
		}
		
		//主线程,即main
		public  void main(int i) throws InterruptedException{
			lock.lock();
			while (isSub!=1) {
				condition1.await();
			}
			for (int j = 0; j < 10; j++) {
				System.out.println("main thread sequence is "+j+" and loop is "+i);
			}
			isSub = 2;
			condition2.signal();
			lock.unlock();
		}
	}

}


 

相关标签: 线程 切换