3. Thread
스레드
- 스레드

Untitled Thread t = new Thread(); t.start();// Runnable 객체를 Thread의 생성자로 전달하여 Runnable에 할당된 작업을 수행하는 // 스레드를 시작 Thread t = new Thread(myRunnableObject); t.start();public class ReturnDigest extends Thread { private String filename; private byte[] digest; public ReturnDigest(String filename) { this.filename = filename; } @Override public void run() { try{ FileInputStream in = new FileInputStream(filename); MessageDigest sha = MessageDigest.getInstance("SHA-256"); DigestInputStream din = new DigestInputStream(in, sha); while(din.read() != -1); din.close(); digest = sha.digest(); } catch (IOException | NoSuchAlgorithmException e) { System.out.println(e); } } public byte[] getDigest() { return digest; } }public class ReturnDigestUserInterface { public static void main(String[] args) { for (String filename : args) { //digest 게산 ReturnDigest returnDigest = new ReturnDigest(filename); returnDigest.start(); //result 출력 StringBuilder result = new StringBuilder(filename); result.append(": "); byte[] digest = returnDigest.getDigest(); result.append(DatatypeConverter.printHexBinary(digest)); System.out.println(result); } } }
- 동기화(synchronize)
//run 메서드 내부에 아래와 같은 코드가 있으면 문제가 될 수 있다. //스레드가 어떤 순서로 리소스를 선점할지가 불확실함. /** 공유자원으로써 동기화 문제 부분 */ System.out.println("input : "); System.out.println(DatatypeConverter.printHexBinary(digest)); System.out.println(); /** end */synchronized (System.out) { /** 공유자원으로써 동기화 문제 부분 */ System.out.println("input : "); System.out.println(DatatypeConverter.printHexBinary(digest)); System.out.println(); /** end */ }public class LogFile { private Writer out; public LogFile(Writer out) { this.out = out; } public LogFile(File f) throws IOException { FileWriter fileWriter = new FileWriter(f); this.out = new BufferedWriter(fileWriter); } /**이 부분에서 동기화 이슈 발생 가능*/ public void writeEntry(String message) throws IOException { Date date = new Date(); out.write(date.toString()); out.write('\\t'); out.write(message); out.write("\\r\\n"); } public void close() throws IOException { out.flush(); out.close(); } } /** 방법1 : Writer의 객체인 out을 동기화 하는 것 */ public void writeEntry(String message) throws IOException { synchronized (out){ Date date = new Date(); out.write(date.toString()); out.write('\\t'); out.write(message); out.write("\\r\\n"); } } /** 방법2 : LogFile 객체 자체를 동기화 */ public void writeEntry(String message) throws IOException { synchronized (this){ Date date = new Date(); out.write(date.toString()); out.write('\\t'); out.write(message); out.write("\\r\\n"); } }
public synchronized void writeEntry(String message) throws IOException { }
- 선점
// 막연히 기다림 public final void join() throws InterruptedException { join(0); } //밀리초를 지정하여 해당 시간만큼 기다림. public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } } public final synchronized void join(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } join(millis); }public final void wait() throws InterruptedException { wait(0L); } public final native void wait(long timeoutMillis) throws InterruptedException; public final void wait(long timeoutMillis, int nanos) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeoutMillis value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0) { timeoutMillis++; } wait(timeoutMillis); }synchronized (someObject) { while (someCondition) { // 특정 조건이 충족될 때까지 대기 someObject.wait(); } // 조건이 충족되면 다음 동작 수행 }
Last updated
