4 스레드 2 더하기 2 빼기

package com.thread;
/**
 *   4   ,       j 1,     j 1
 * 
 *
 */
public class ThreadTest2 {
	
	//       j,        
	private int j; 
	
	public static void main(String[] args) {
		/**
		 *            ,        
		 *                  ,
		 *                         ,
		 *           ,            ,
		 *              +   + new              
		 */
		ThreadTest2 test2=new ThreadTest2();
		Inc inc=test2.new Inc();
		Dec dec=test2.new Dec();
		for (int i = 0; i < 2; i++) {
			new Thread(inc).start();
			new Thread(dec).start();
		}
	}
	
	
	/**
	 *  1  
	 */
	public synchronized void inc() {
		j++;
		System.out.println(Thread.currentThread().getName()+":inc()="+j);
	}
	
	/**
	 *  1  
	 */
	public synchronized void dec() {
		j--;
		System.out.println(Thread.currentThread().getName()+":dec()="+j);
	}
	
	
	
// 1    
	class Inc implements Runnable{
		public void run() {
			for (int i = 0; i < 10; i++) {
				inc();
			}
		}
	}
	
// 1    
	class Dec implements Runnable{
		public void run() {
			for (int i = 0; i < 10; i++) {
				dec();
			}
		}
	}
}

좋은 웹페이지 즐겨찾기