多线程通过synchronized来控制执行顺序

  • Post author:
  • Post category:其他


package helloword;

import java.util.*;

public class Main {
	private static Object mLock = new Object();
	private static Object mLock1 = new Object();
	private static Object mLock2 = new Object();
	private static Object mLock3 = new Object();
	private static int count =0;
	public static void main(String[] args) {
		mTh1.start();
		mTh2.start();
		mTh3.start();
		synchronized (mLock1) {
			try {
				mLock1.wait(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			mLock1.notify();
		}
		synchronized (mLock) {
			try {
				mLock.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}			
		}
		try {
			System.out.println("mTh1.join()");
			mTh1.join();
			System.out.println("mTh2.join()");
			mTh2.join();
			System.out.println("mTh3.join()");
			mTh3.join();		
			System.out.println("mTh4.join()");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
		System.out.println("main --end");
	}
	static Thread mTh1 = new Thread(new Runnable() {
		
		@Override
		public void run() {
			while(true) {
				synchronized (mLock1) {
					try {
						mLock1.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}					
				}
				System.out.print("A");
				synchronized (mLock2) {					
					mLock2.notify();					
				}					
			}
		

		}
	});
	static Thread mTh2 = new Thread(new Runnable() {
		
		@Override
		public void run() {
			while(true) {
				synchronized (mLock2) {
					try {
						mLock2.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}					
				}
				System.out.print("B");
				synchronized (mLock3) {
					
					mLock3.notify();
				}				
			}

		}
	});
	static Thread mTh3 = new Thread(new Runnable() {
		
		@Override
		public void run() {
			while(true) {
				synchronized (mLock3) {
					try {
						mLock3.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}					
				}
				System.out.print("C");
				if(count++>3) {
					synchronized (mLock) {
						mLock.notify();
					}						
				}else {
					synchronized (mLock1) {						
						mLock1.notify();
					}						
				}

			}

		}
	});	
}



版权声明:本文为andylao62原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。