나는 다음과 같은 코드가 있습니다스레딩 및 동기화 방법
public class MyThread extends Thread {
private int i;
public static int sum=0;
public MyThread(int k){
i=k;
}
public static void main(String[] args) throws InterruptedException{
Thread t=new MyThread(1);
Thread s=new MyThread(2);
Thread p=new MyThread(3);
t.start();
s.start();
}
public synchronized void doSomething(){
for(int i=0; i<100000; i++){
System.out.println(this.i);
}
}
@Override
public void run() {
doSomething();
}
}
해봐요가 동기화됩니다. 왜 출력이 무작위입니까? 동기화 된 메서드는 동기화 된 블록과 같지만 블록의 출력은 동기화되어 있고 메서드는 그렇지 않습니다.
'임의'란 무엇을 의미합니까? 코드에서 3 개의 쓰레드가 실행 중이며, 각각은 프로세서 시간을 할당 받게되므로 출력은 인터리브 될 것입니다. – Nick
@mary : 예제를 확인하십시오! –