Hirdetés

Keresés

Új hozzászólás Aktív témák

  • loszerafin
    senior tag

    nezd meg ezt:


    class Main {
    static int cnt = 0;
    static boolean end = false;
    static Object lock = new Object();

    static class ModCounter extends Thread {
    public void run() {
    while(!end) {
    synchronized (lock) {
    cnt += 1;
    System.out.println(cnt);
    cnt -= 1;
    }
    }
    }
    }

    public static void main(String[] args)
    throws InterruptedException{
    ModCounter modc = new ModCounter();
    ModCounter modc2 = new ModCounter();
    modc.start();
    modc2.start();

    Thread.sleep(500);

    end = true;

    }
    }

    [Szerkesztve]

    Köszönöm, valóban jó megoldás egy lock objektum létrehozása:


    class Counter3 {
    static int cnt = 0;
    static boolean end = false;
    static Object lock = new Object();

    static class ModCounter implements Runnable {
    public void run() {
    while(!end){
    synchronized (lock) {
    cnt += 1;
    cnt -= 1;
    }
    }
    }
    }

    public static void main(String[] args)
    throws InterruptedException{
    ModCounter modc = new ModCounter();
    Thread t1 = new Thread(modc);

    t1.start();

    for(int i=0; i<10; i++){
    Thread.sleep(500);
    synchronized (lock) {
    System.out.println(cnt);
    };
    };
    end = true;

    t1.join();
    System.out.println(cnt);
    }
    }



  • loszerafin
    senior tag

    nezd meg ezt:


    class Main {
    static int cnt = 0;
    static boolean end = false;
    static Object lock = new Object();

    static class ModCounter extends Thread {
    public void run() {
    while(!end) {
    synchronized (lock) {
    cnt += 1;
    System.out.println(cnt);
    cnt -= 1;
    }
    }
    }
    }

    public static void main(String[] args)
    throws InterruptedException{
    ModCounter modc = new ModCounter();
    ModCounter modc2 = new ModCounter();
    modc.start();
    modc2.start();

    Thread.sleep(500);

    end = true;

    }
    }

    [Szerkesztve]

    Köszönöm, hogy foglalkozol a témával.

    Közben kitaláltam egy megoldást (egy oldallal tovább kellett olvasnom a könyvben a wait()-ig)


    class Counter2 {
    static int cnt = 0;
    static boolean end = false;

    static class ModCounter implements Runnable {
    public void run() {
    while(!end){
    synchronized (this) {
    cnt += 1;
    cnt -= 1;
    notify();
    }
    }
    }
    }

    public static void main(String[] args)
    throws InterruptedException{
    ModCounter modc = new ModCounter();
    Thread t1 = new Thread(modc);

    t1.start();

    for(int i=0; i<10; i++){
    Thread.sleep(500);
    synchronized (modc) {
    modc.wait();
    System.out.println(cnt);
    };
    };
    end = true;

    t1.join();
    System.out.println(cnt);
    }
    }



Új hozzászólás Aktív témák