스레드 범위 내 공유 변수
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 각자 금액 인출
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 라인과synchronized 키워드를 깊이 있게 설명하다루틴이야말로 프로그램의 집행자이고 여러 루틴 간에 프로세스 중의 자원을 공유하고 있다.하나의 cpu는 동시에 하나의 라인만 실행할 수 있으며, 모든 라인은 하나의 타임 슬라이스가 있으며, 타임 슬라이스가 다 사용하면...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.