---
title: "java 线程等待原理"
author: "大器晚成"
date: "2011-06-09T10:08:53Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-06-09T10:09:23Z"
id: 1073927
url: "https://snake.iteye.com/blog/1073927"
---

```java

public class TestThread {
	
	int count=0;
	Object lock=new Object();
	transient boolean isWorking=true;
	Thread t1=new Thread(){
		public void run() {
			while(true){
				try {
					if(count++%10==0){
						System.out.println("睡觉");
						isWorking=false;
						synchronized (lock) {
							lock.wait();
						}
						isWorking=true;
						System.out.println("睡醒了");
					}else{
						System.out.println("睡"+count);
						Thread.sleep(100);
					}	
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	Thread t2=new Thread(){
		public void run() {
			while (true) {
				try {
					if(!isWorking){
						System.out.println("醒醒啦！");
						synchronized (lock) {
						lock.notify();
						}
					}
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	public TestThread() {
		t1.start();
		t2.start();
	}
	public static void main(String[] args) {
		new TestThread();
	}
}

```


public class TestThread {
	
	int count=0;
	Object lock=new Object();
	transient boolean isWorking=true;
	Thread t1=new Thread(){
		public void run() {
			while(true){
				try {
					if(count++%10==0){
						System.out.println("睡觉");
						isWorking=false;
						synchronized (lock) {
							lock.wait();
						}
						isWorking=true;
						System.out.println("睡醒了");
					}else{
						System.out.println("睡"+count);
						Thread.sleep(100);
					}	
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	Thread t2=new Thread(){
		public void run() {
			while (true) {
				try {
					if(!isWorking){
						System.out.println("醒醒啦！");
						synchronized (lock) {
						lock.notify();
						}
					}
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	public TestThread() {
		t1.start();
		t2.start();
	}
	public static void main(String args) {
		new TestThread();
	}
}