1. 程式人生 > >設計四個線程,當中共兩個線程每次對j添加1,另外兩個線程每次對j降低1。循環100次,寫出程序。

設計四個線程,當中共兩個線程每次對j添加1,另外兩個線程每次對j降低1。循環100次,寫出程序。

public read 設計 test6 ng- -m popu div for

package cn.usst.DataTest6;

/**
 * 設計四個線程,當中共兩個線程每次對j添加1,另外兩個線程每次對j降低1。循環100次,寫出程序。
 * @
 *
 */
public class DataTest6 {
	private int j;
	public static void main(String[] args) {
		DataTest6 dt = new DataTest6();
		Inc inc = dt.new Inc();
		Dec dec = dt.new Dec();
		
		for(int i=0;i < 2; i++){
			Thread t = new Thread(inc);
			t.start();
			t = new Thread(dec);
			t.start();
		}
	}
	
	class Inc implements Runnable{
		public void run() {
			for(int i=0; i<100; i++){
				inc();
			}
		}
	}
	
	class Dec implements Runnable{
		public void run() {
			for(int i=0; i<100; i++){
				dec();
			}
		}
	}
	
	private synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName() + " +inc: " + j);
	}
	
	private synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName() + " -dec: " + j);
	}
}

設計四個線程,當中共兩個線程每次對j添加1,另外兩個線程每次對j降低1。循環100次,寫出程序。