스레드 범위 내 공유 변수

3227 단어 라인
package com.itcast;

import java.util.Random;

public class ThreadScopeShareMoney {

	/**
	 * @param args
	 */
	private static int money = 0;
	public static void main(String[] args) {
		for(int i =0;i<2;i++){
	    new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				money = new Random().nextInt();  
				System.out.println(Thread.currentThread().getName()+ " put money: " + money); 
				new A().get();
				new B().get();
			}
		}).start();
	    }
	}
	 static class A {
		public void get() {
			System.out.println("A from " + Thread.currentThread().getName()
					+ " put money:" + money);
		}
	}

	static class B {
		public void get() {
			System.out.println("B from " + Thread.currentThread().getName()
					+ " put money: " + money);
		}
	}
}

    : 
Thread-1 put money: 1977754500
Thread-0 put money: -658790150
A from Thread-1 put money:-658790150
A from Thread-0 put money:-658790150
B from Thread-1 put money: -658790150
B from Thread-0 put money: -658790150

그 결과 스레드 0과 스레드 -1의 A와 B 추출이 모두 같은 데이터로 오류가 발생했고 스레드가 동기화되지 않았다.
 
package com.itcast;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadScopeShareMoney {

	/**
	 * @param args
	 */
	private static int money = 0;
	private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>(); //  Map  
	public static void main(String[] args) {
		for(int i =0;i<2;i++){
	    new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				int money = new Random().nextInt();  
				System.out.println(Thread.currentThread().getName()+ " put money: " + money); 
				threadData.put(Thread.currentThread(), money);    //                ,    
				new A().get();
				new B().get();
			}
		}).start();
	    }
	}
	 static class A {
		public void get() {
			int money = threadData.get(Thread.currentThread());     //    
			System.out.println("A from " + Thread.currentThread().getName()
					+ " put money:" + money);
		}
	}

	static class B {
		public void get() {
			int money = threadData.get(Thread.currentThread());     //    
			System.out.println("B from " + Thread.currentThread().getName()
					+ " put money: " + money);
		}
	}
}
   :
Thread-0 put money: 37664812
Thread-1 put money: -1336612286
A from Thread-0 put money:37664812
A from Thread-1 put money:-1336612286
B from Thread-1 put money: -1336612286
B from Thread-0 put money: 37664812

A와 B 온라인 스레드 0과 스레드-1 각자 금액 인출

좋은 웹페이지 즐겨찾기