기본 콘텐츠로 건너뛰기

3월, 2016의 게시물 표시

스레드 동기화2 - volatile, Atomic

참고 : 이펙티브자바  (규칙66 변경 가능 공유 데이터에 대한 접근은 동기화하라) 이펙티브자바에서는 스레드를 중지할때 Thread.stop() 함수를 사용하지 말라고 강조한다. 뭔가 안전하지 않다는 이유다. 대신 반복문으로 이를 해결하라고 당부한다. 반복문으로 실행하는 스레드 예를들어, 스레드를 하나 생성하여 실행한다. 외부에서 스레드의 실행조건(반복문)을 변경하고자 한다. 스레드는 실행조건이 변경을 감지하고 실행을 종료한다. public class D { 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 .

스레드 동기화1 - syncronized

구현 스레드를 구현하는 방법은 2가지다. 1. Thread 클래스를 extends 한다. 2. Runnable 인터페이스를 implements 한다. 뭐 사실 Thread는 생성자의 변수로 Runnable을 취한다. public Thread (Runnable target) { init( null, target , "Thread-" + nextThreadNum () , 0 ) ; } 그리고 Runnable 인터페이스는 run() 이라는 단일함수를 갖는 인터페이스이다. @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code> Runnable </code> is used * to create a thread, starting the thread causes the object's * <code> run </code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code> run </code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run () ; } 그렇기 때문에 람다식으로 표현이 가능한 것이다. 동기화 동기화는 동시에 같은자원의 접근을 제한하고자 할때 사용한다. 예를들어, 한 우물에서 물을 15번 길어야 하는 일을 해야할때 5명이서 3번만 하면 수고를 5배로 줄일수 있다. 그런데 우물은 하난데 동시에