欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程----wait/notify

程序员文章站 2023-12-23 11:36:40
...
线程同步:两个线程依次对同一变量进行操作。

package com.thread.waitNotify;

/**
 * 线程一对变量加1,线程二对该变量减1,如此循环下去
 * 
 * @author yangjianzhou
 * @description TODO
 * @time Nov 6, 2014 : 9:39:53 PM
 */
public class ThreadTest1 {

	public static void main(String[] args) {
		final AssistClass assist = new AssistClass();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					assist.plus();
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					assist.minus();
				}
			}
		}).start();
	}
}

class AssistClass {
	boolean runPlus = true;
	
	private int amount;
    /**
     * execute ++amount ,then print the field
     */
	public synchronized void plus() {
		if (!runPlus) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("plus method : amount = " + (++amount));
		runPlus = false;
		this.notify();
	}

    /**
     * execute --amount ,then print the field
     */
	public synchronized void minus() {
		if (runPlus) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("minus method : amount = " + (--amount));
		runPlus = true;
		this.notify();
	}

}



运行结果:
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0
plus method : amount = 1
minus method : amount = 0

上一篇:

下一篇: