Skip to content

Instantly share code, notes, and snippets.

@ch7895
Created March 23, 2016 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ch7895/39b13b8d80128457fdb8 to your computer and use it in GitHub Desktop.
Save ch7895/39b13b8d80128457fdb8 to your computer and use it in GitHub Desktop.
스레드 동기화 예제2 - volatile, Atomic
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;
}
}
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;
}
}
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();
}
}
@ch7895
Copy link
Author

ch7895 commented Mar 23, 2016

@ch7895
Copy link
Author

ch7895 commented Mar 23, 2016

class A는
스레드 동기화 예제1 - syncronized 의 A에서 수정

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment