[자바기초] 쓰레드를 활용한 교차 출력


ThreadMain

package MyTread;
 
public class MyTread {
    public static void main(String[] args) {
        Cnt cnt = new Cnt();
        new PrintThread(cnt).start();
        new UpThread(cnt).start();
    }
}
Cnt

package MyTread;
 
public class Cnt {
    /*
     * 두 스레드가 공유하는 클래스
     */
     
    public final static int MAX = 100;
    private int cnt = 0;
 
    // wait(), notify()를 사용하기 위해서는 synchronized가 적용된 메소드만 가능
     
    // cnt가 30일 때 wait();
    public synchronized void doWait() {
        if (cnt == 30) {
            try {
                System.out.println("wait()");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
     
    // cnt가 60일 때 notify();
    public synchronized void doNotify() {
        if (cnt == 60) {
            notify();
            System.out.println("notify()");
        }
    }
 
    @Override
    public String toString() {
        return "cnt : " + cnt;
    }
 
    public int getCnt() {
        return cnt;
    }
 
    public void setCnt(int cnt) {
        this.cnt = cnt;
    }
}
PrintThread

package MyTread;
 
public class PrintThread implements Runnable {
    /*
     * cnt를 출력해주는 스레드
     */
 
    private Thread th = null;
    private Cnt cnt;
 
    public PrintThread(Cnt cnt) {
        this.cnt = cnt;
    }
     
    @Override
    public void run() {
        while (cnt.getCnt() < Cnt.MAX) {
            try {
                System.out.println(cnt);
                // wait();
                cnt.doWait();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    public void start() {
        th = new Thread(this);
        th.start();
    }
}
UpThread

package MyTread;
 
public class UpThread implements Runnable {
    /*
     * cnt를 증가시켜주는 스레드
     */
 
    private Thread th = null;
    private Cnt cnt;
 
    public UpThread(Cnt cnt) {
        this.cnt = cnt;
    }
 
    @Override
    public void run() {
        while (cnt.getCnt() < Cnt.MAX) {
            try {
                cnt.setCnt(cnt.getCnt() + 1);
                // notify();
                cnt.doNotify();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    public void start() {
        th = new Thread(this);
        th.start();
    }
}

댓글

이 블로그의 인기 게시물

[자바기초] jxl을 이용하여 자바에서 엑셀파일 읽고,쓰기

[자바기초] Vector, Iterator를 이용해서 정수 삽입후 모든 정수 출력 및 합산

[자바기초] HashMap으로 [학생 이름, Student 객체]를 이용하여 저장, 출력