Sunday, May 5, 2013

H11112277-04-PEMOGRAMAN



1.       Syntaks:
package tugaspakarmin;
import java.util.logging.*;
public class konkurensi implements Runnable {

    //
    public static int countwriter = 0;
    public static int countreader = 0;
    //
    public static final int READER = 0;
    public static final int WRITER = 1;
    //
    private int type;
    private int id;
    private String strid;

    public konkurensi (int type) {
        this.type = type;
        this.strid = (type == READER) ? ("Reader " + (this.id = ++countreader)) : ("Writer " + (this.id = ++countwriter));
    }

    public static void main(String[] argv) {
        (new Thread(new konkurensi(READER))).start();
        (new Thread(new konkurensi(READER))).start();
        (new Thread(new konkurensi(WRITER))).start();
    }

    public void run() {
        if (type == READER) {
            read();
        } else if (type == WRITER) {
            write();
        }
    }

    //*********************************************************
    // Reader
    //*********************************************************
    /**
     *
     */
    public void read() {
        System.out.println(strid + ": start!");
        while (true) {
            System.out.println(strid + ": reading!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(konkurensi.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    //*********************************************************
    //*********************************************************
    // Writer
    //*********************************************************

    public void write() {
        System.out.println(strid + ": start!");
        while (true) {
            System.out.println(strid + ": writing!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(konkurensi.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    //*********************************************************
}

2.       Program :