ITeye博客

如何让两个线程交替运行

wangxuefang · 2013-09-26 14:28 · java · 编程语言 · Markdown

之前碰到过这样的问题:同时启动两个线程,那么如何让两个线程交替执行呢?

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();

	}

 这里主要用到的同步锁的知识点。一个对象只有一把锁,两个线程交替获取同一个对象的锁,从而交替运行同步方法,达到线程交替运行的目的。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。