如何讓兩個線程交替運行

之前碰到過這樣的問題:同時啓動兩個線程,那麼如何讓兩個線程交替執行呢?

public class ThreadWaitTest {

	public static class StarterThread implements Runnable {
		private Object lock = null;

		public StarterThread(Object lock) {
			this.lock = lock;
		}

		public void run() {
			System.out.println("start..");
			/*for(int i =0; i<50; i++){
	            System.out.println("start:"+i);
	        }*/
			synchronized (lock) {
				try {
					for (int i = 0; i < 50; i++) {
						System.out.println("start:" + i);
						lock.notifyAll();
						lock.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
	}

	public static class EnderThread implements Runnable {
		private Object lock = null;

		public EnderThread(Object lock) {
			this.lock = lock;
		}

		public void run() {
			System.out.println("end..");
			/*for(int i =0; i<50; i++){
	            System.out.println("end:"+i);
	        }*/
			synchronized (lock) {
				for (int i = 0; i < 50; i++) {
					System.out.println("end:" + i);
					lock.notifyAll();
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		Object lock = new Object();
		Thread starterThread = new Thread(new StarterThread(lock));
		Thread enderThread = new Thread(new EnderThread(lock));
		starterThread.start();
		enderThread.start();

	}

 這裏主要用到的同步鎖的知識點。一個對象只有一把鎖,兩個線程交替獲取同一個對象的鎖,從而交替運行同步方法,達到線程交替運行的目的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章