Created
March 23, 2016 11:36
-
-
Save ch7895/39b13b8d80128457fdb8 to your computer and use it in GitHub Desktop.
스레드 동기화 예제2 - volatile, Atomic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* Created by chkyu on 2016-03-22. | |
*/ | |
public class A { | |
private static AtomicInteger a ; | |
A(){ | |
a=new AtomicInteger(15); | |
} | |
public void work(){ | |
//a--; | |
a.decrementAndGet(); | |
} | |
public AtomicInteger getA(){ | |
return a; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.TimeUnit; | |
public class D { | |
private static volatile boolean stopRequested=false; | |
//private static boolean stopRequested=false; | |
private static void requestStop(){ | |
stopRequested = true; | |
} | |
private static boolean stopRequested(){ | |
return stopRequested; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
Thread backThread = new Thread(new Runnable(){ | |
public void run(){ | |
int i=0; | |
System.out.println(2); | |
while(!stopRequested) | |
i++; | |
System.out.println(4+"/"+i); | |
} | |
}); | |
backThread.start(); | |
System.out.println(1); | |
TimeUnit.SECONDS.sleep(1); | |
System.out.println(3); | |
stopRequested = true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.TimeUnit; | |
public class E { | |
private static boolean stopRequested; | |
private static synchronized void requestStop(){ | |
stopRequested = true; | |
} | |
private static synchronized boolean stopRequested(){ | |
return stopRequested; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
Thread backThread = new Thread(new Runnable(){ | |
public void run(){ | |
int i=0; | |
System.out.println(2); | |
while(!stopRequested()) | |
i++; | |
System.out.println(4+"/"+i); | |
} | |
}); | |
backThread.start(); | |
System.out.println(1); | |
TimeUnit.SECONDS.sleep(1); | |
System.out.println(3); | |
requestStop(); | |
} | |
} |
class A는
스레드 동기화 예제1 - syncronized 의 A에서 수정
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://changpd.blogspot.kr/2016/03/2-volatile-atomic.html