10.스레드의 동기화및 필요성
스레드의 동기화및 필요성
하나의 프로세스 안에서 개별적으로 스레드를 마련
힙과 정적영역은 공유한다
스텍은 공유하지 않고 개별적으로 사용
스텍 :자기자신만 영향을 준다
이때 힙과 정적영역에 문제가 발생한다
package part2;
public class Proagram1 {
public static void main(String[] args) {
Runnable subMain = new Runnable() {
@Override
public void run() {
print();
}
};
// 스레드 그룹
Thread th1 = new Thread(subMain);
th1.setName("sub1");
Thread th2 = new Thread(subMain);
th2.setName("sub2");
th1.start(); // 꼭 있어야 한다
th2.start(); // 꼭 있어야 한다
Thread th = Thread.currentThread();
th.setName("Main");
// print();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//
e.printStackTrace();
////
}
// if (th1.isAlive())
// th1.interrupt();
// if (th2.isAlive())
// th2.interrupt();
// if (th3.isAlive())
// th3.interrupt();
// if (th4.isAlive())
// th4.interrupt();
// if (th5.isAlive())
// th5.interrupt();
// if (th6.isAlive())
// th6.interrupt();
System.out.println("=====exit=====");
}
static int gIndex = 0;// 데이터/정적영역에(모든스레드가 같이 공유한다)
private static void print() {
int index = 0;// 스텍에 (스레드별로 마련됨)
Thread th = Thread.currentThread();
for (int i = 0; i < 100; i++) {
if (th.isInterrupted()) {
System.err.println("요청이 들어와서 종료함");
return;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.err.println("자다가깨서 종료함."); // 자고있는데 interrupt가 처리해서 깨움
return;
}
// 메인일 경우 다르게 호출하고 싶을경우
index++;
gIndex++;
System.out.printf("%s[%d] : %d, index:%d,gIndex: %d\n", th.getName(), th.getId(), i + 1, index, gIndex);
}
}
}
sub1[14] : 98, index:98,gIndex: 193
sub2[15] : 99, index:99,gIndex: 194
sub1[14] : 99, index:99,gIndex: 195
sub2[15] : 100, index:100,gIndex: 196
sub1[14] : 100, index:100,gIndex: 197
각각의 스레드가 동시에 실행하면서 증가시키다 멈추고 출력하기전에 다른 스레드가 개입해서 건들이면서 번호가 서로 영향을 주기 때문에 동시성 문제 발생한다
동시성 문제 발생 :여러개가 동시에 실행하는 과정에서 하나의 자원을 공유하면 문제 발생한다
한번에 같이 쓰지말고 줄세워서 쓰게 하자 : 동기화한다
전에는 비동기화
댓글남기기