---
title: "Thread common example"
author: "fairy_xzc"
date: "2012-08-02T16:48:57Z"
tags: []
categories: ["编程语言"]
slug: "thread-common-example"
draft: false
lastmod: "2012-08-02T19:32:30Z"
id: 1617302
url: "https://agilestyle.iteye.com/blog/1617302"
---

1.设计 4 个线程，其中两个线程每次对 j增加1，另外两个线程对j每次减少1。

```
public class ThreadTest {
	public static void main(String[] args) {
		MyThread thread = new MyThread();

		for (int i = 0; i < 2; i++) {
			Thread inc = new Thread(new Inc(thread));
			Thread dec = new Thread(new Dec(thread));

			inc.start();
			dec.start();
		}
	}
}

class MyThread {
	private int j;

	public synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName() + "-dec:" + j);
	}

	public synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName() + "-inc:" + j);
	}
}

class Dec implements Runnable {

	private MyThread obj;

	public Dec(MyThread obj) {
		this.obj = obj;
	}

	@Override
	public void run() {
		this.obj.dec();
	}
}

class Inc implements Runnable {

	private MyThread obj;

	public Inc(MyThread obj) {
		this.obj = obj;
	}

	@Override
	public void run() {
		this.obj.inc();
	}
}
```

 

2.设计两个线程，第一个线程从1加到10，在这加的过程中，第二个线程必须等待，当第一个线程加到10时，第二个线程启动，从10减到1，在这减的过程中，第一个线程必须等待，循环执行若干时间后，退出程序。

```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadTest {
	public static void main(String[] args) throws Exception {
		final Num num = new Num();
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new Runnable() {

			@Override
			public void run() {
				try {
					while (!Thread.interrupted()) {
						TimeUnit.MILLISECONDS.sleep(200);
						num.increased();
						num.waitForDecreasing();
					}
				} catch (InterruptedException e) {
					System.out.println("Exiting via interrupt");
				}
				System.out.println("Ending Increase");

			}
		});

		exec.execute(new Runnable() {

			@Override
			public void run() {
				try {
					while (!Thread.interrupted()) {
						num.waitForIncreasing();
						TimeUnit.MILLISECONDS.sleep(200);
						num.decreased();
					}
				} catch (InterruptedException e) {
					System.out.println("Exiting via interrupt");
				}
				System.out.println("Ending Decrease");

			}
		});

		TimeUnit.SECONDS.sleep(5); // Run for a while...
		exec.shutdownNow(); // Interrupt all tasks
	}
}

class Num {
	private boolean flag = false;
	private int i;

	public synchronized void increased() {
		flag = true;

		for (i = 1; i < 11; i++) {
			System.out.println(Thread.currentThread().getName() + "-inc " + i);
		}

		notifyAll();
	}

	public synchronized void decreased() {
		flag = false;

		for (i = 10; i > 0; i--) {
			System.out.println(Thread.currentThread().getName() + "-dec " + i);
		}

		notifyAll();
	}

	public synchronized void waitForIncreasing() throws InterruptedException {
		while (flag == false)
			wait();
	}

	public synchronized void waitForDecreasing() throws InterruptedException {
		while (flag == true)
			wait();
	}
}
```