---
title: "如何让两个线程交替运行"
author: "wangxuefang"
date: "2013-09-26T14:28:36Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-09-26T14:28:36Z"
id: 1947610
url: "https://wangxuefang.iteye.com/blog/1947610"
---

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

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

	}
```

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