23

以下のコードを試しました。このコードは、著者によると正しい他の投稿から取得しました。しかし、実行しようとすると、正確な結果が得られません。

これは主に、偶数と奇数の値を順番に出力するためのものです。

public class PrintEvenOddTester {



    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }


}



class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}

誰かがこれを修正するのを手伝ってくれますか?

編集 期待される結果: 奇数:1 偶数:2 奇数:3 偶数:4 奇数:5 偶数:6 奇数:7 偶数:8 奇数:9

4

41 に答える 41

54

解決策を見つけました。この問題の解決策を探している人は参照できます:-)

public class PrintEvenOddTester {

    public static void main(String... args) {
        Printer print = new Printer();
        Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
        Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    private int max;
    private Printer print;
    private boolean isEvenNumber;

    TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
        this.print = print;
        this.max = max;
        this.isEvenNumber = isEvenNumber;
    }

    @Override
    public void run() {

        //System.out.println("Run method");
        int number = isEvenNumber == true ? 2 : 1;
        while (number <= max) {

            if (isEvenNumber) {
                //System.out.println("Even :"+ Thread.currentThread().getName());
                print.printEven(number);
                //number+=2;
            } else {
                //System.out.println("Odd :"+ Thread.currentThread().getName());
                print.printOdd(number);
                // number+=2;
            }
            number += 2;
        }

    }

}

class Printer {

    boolean isOdd = false;

    synchronized void printEven(int number) {

        while (isOdd == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:" + number);
        isOdd = false;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while (isOdd == true) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:" + number);
        isOdd = true;
        notifyAll();
    }

}

これにより、次のような出力が得られます。

Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10
于 2013-05-23T05:25:06.673 に答える
13

これは、単一のクラスで機能するようにしたコードです

package com.learn.thread;

public class PrintNumbers extends Thread {
volatile static int i = 1;
Object lock;

PrintNumbers(Object lock) {
    this.lock = lock;
}

public static void main(String ar[]) {
    Object obj = new Object();
    // This constructor is required for the identification of wait/notify
    // communication
    PrintNumbers odd = new PrintNumbers(obj);
    PrintNumbers even = new PrintNumbers(obj);
    odd.setName("Odd");
    even.setName("Even");
    odd.start();
    even.start();
}

@Override
public void run() {
    while (i <= 10) {
        if (i % 2 == 0 && Thread.currentThread().getName().equals("Even")) {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + " - "
                        + i);
                i++;
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (i % 2 == 1 && Thread.currentThread().getName().equals("Odd")) {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + " - "
                        + i);
                i++;
                lock.notify();
              }
           }
        }
    }
}

出力:

Odd - 1
Even - 2
Odd - 3
Even - 4
Odd - 5
Even - 6
Odd - 7
Even - 8
Odd - 9
Even - 10
Odd - 11
于 2015-05-05T16:01:35.210 に答える
3

最も簡単な解決策!!

public class OddEvenWithThread {
    public static void main(String a[]) {
        Thread t1 = new Thread(new OddEvenRunnable(0), "Even Thread");
        Thread t2 = new Thread(new OddEvenRunnable(1), "Odd Thread");

        t1.start();
        t2.start();
    }
}

class OddEvenRunnable implements Runnable {
    Integer evenflag;
    static Integer number = 1;
    static Object lock = new Object();

    OddEvenRunnable(Integer evenFlag) {
        this.evenflag = evenFlag;
    }

    @Override
    public void run() {
        while (number < 10) {
            synchronized (lock) {
                try {
                    while (number % 2 != evenflag) {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}
于 2020-06-16T14:10:26.870 に答える
2

Lock インターフェイスでも同じことができます。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class NumberPrinter implements Runnable {
    private Lock lock;
    private Condition condition;
    private String type;
    private static boolean oddTurn = true;

    public NumberPrinter(String type, Lock lock, Condition condition) {
        this.type = type;
        this.lock = lock;
        this.condition = condition;
    }

    public void run() {
        int i = type.equals("odd") ? 1 : 2;
        while (i <= 10) {
            if (type.equals("odd"))
                printOdd(i);
            if (type.equals("even"))
                printEven(i);
            i = i + 2;
        }
    }

    private void printOdd(int i) {
        // synchronized (lock) {
        lock.lock();
        while (!oddTurn) {
            try {
                // lock.wait();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(type + " " + i);
        oddTurn = false;
        // lock.notifyAll();
        condition.signalAll();
        lock.unlock();
    }

    // }

    private void printEven(int i) {
        // synchronized (lock) {
        lock.lock();
        while (oddTurn) {
            try {
                // lock.wait();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(type + " " + i);
        oddTurn = true;
        // lock.notifyAll();
        condition.signalAll();
        lock.unlock();
    }

    // }

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread odd = new Thread(new NumberPrinter("odd", lock, condition));
        Thread even = new Thread(new NumberPrinter("even", lock, condition));
        odd.start();
        even.start();
    }
}
于 2014-05-03T07:54:32.747 に答える
1

他の質問は、この質問の重複としてクローズされました。wait/notify「偶数または奇数」の問題を安全に取り除き、次のように構成を使用できると思います。

public class WaitNotifyDemoEvenOddThreads {
    /**
     * A transfer object, only use with proper client side locking!
     */
    static final class LastNumber {
        int num;
        final int limit;

        LastNumber(int num, int limit) {
            this.num = num;
            this.limit = limit;
        }
    }

    static final class NumberPrinter implements Runnable {
        private final LastNumber last;
        private final int init;

        NumberPrinter(LastNumber last, int init) {
            this.last = last;
            this.init = init;
        }

        @Override
        public void run() {
            int i = init;
            synchronized (last) {
                while (i <= last.limit) {
                    while (last.num != i) {
                        try {
                            last.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + " prints: " + i);
                    last.num = i + 1;
                    i += 2;
                    last.notify();
                }
            }
        }
    }

    public static void main(String[] args) {
        LastNumber last = new LastNumber(0, 10); // or 0, 1000
        NumberPrinter odd = new NumberPrinter(last, 1);
        NumberPrinter even = new NumberPrinter(last, 0);
        new Thread(odd, "o").start();
        new Thread(even, "e").start();
    }
}
于 2016-03-23T16:02:26.903 に答える
0

次のコードを使用して、2 つの匿名スレッド クラスを作成して出力を取得できます。

package practice;

class Display {
    boolean isEven = false;

    synchronized public void printEven(int number) throws InterruptedException {
        while (isEven)
            wait();
        System.out.println("Even : " + number);
        isEven = true;
        notify();
    }

    synchronized public void printOdd(int number) throws InterruptedException {
        while (!isEven)
            wait();
        System.out.println("Odd : " + number);
        isEven = false;
        notify();
    }
}

public class OddEven {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final Display disp = new Display();


        new Thread() {
            public void run() {
                int num = 0;
                for (int i = num; i <= 10; i += 2) {
                    try {
                        disp.printEven(i);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                int num = 1;
                for (int i = num; i <= 10; i += 2) {
                    try {
                        disp.printOdd(i);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}
于 2016-10-23T06:37:25.877 に答える
0
package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}
于 2016-06-24T09:53:14.103 に答える
0

以下は、2 つのセマフォを使用した私の実装です。

  1. パーミット 1 の奇数セマフォ。
  2. パーミット 0 のセマフォでも。
  3. 次の署名 (my、other) として、2 つのセマフォを両方のスレッドに渡します。
  4. 奇数スレッドへ 順番に (奇数、偶数)
  5. 偶数スレッドへ この順序でパスします (偶数、奇数)
  6. run() メソッドのロジックは my.acquireUninterruptively() -> Print -> other.release() です
  7. 偶数スレッドでは、偶数セマが 0 であるため、ブロックされます。
  8. Odd スレッドでは、Odd Sema が使用可能であるため (init を 1)、1 を出力してから、Even Sema を解放して、Even スレッドを実行できるようにします。
  9. 偶数スレッドの実行は 2 を出力し、奇数の Sema を解放して、奇数のスレッドを実行できるようにします。

    import java.util.concurrent.Semaphore;
    
    
    public class EvenOdd {
    private final static String ODD = "ODD";
    private final static String EVEN = "EVEN";
    private final static int MAX_ITERATIONS = 10;
    
    public static class EvenOddThread implements Runnable {     
        private String mType;
        private int  mNum;
        private Semaphore mMySema;
        private Semaphore mOtherSema;
    
        public EvenOddThread(String str, Semaphore mine, Semaphore other) {
            mType = str;
            mMySema = mine;//new Semaphore(1); // start out as unlocked
            mOtherSema = other;//new Semaphore(0);
            if(str.equals(ODD)) {
                mNum = 1;
            }
            else {
                mNum = 2;
            }
        }
    
        @Override
        public void run() {         
    
                for (int i = 0; i < MAX_ITERATIONS; i++) {
                    mMySema.acquireUninterruptibly();
                    if (mType.equals(ODD)) {
                        System.out.println("Odd Thread - " + mNum);
                    } else {
                        System.out.println("Even Thread - " + mNum);
                    }
                    mNum += 2;
                    mOtherSema.release();
                }           
        }
    
    }
    
        public static void main(String[] args) throws InterruptedException {
            Semaphore odd = new Semaphore(1);
            Semaphore even = new Semaphore(0);
    
            System.out.println("Start!!!");
            System.out.println();
    
            Thread tOdd = new Thread(new EvenOddThread(ODD, 
                                     odd, 
                                     even));
            Thread tEven = new Thread(new EvenOddThread(EVEN, 
                                     even, 
                                     odd));
    
            tOdd.start();
            tEven.start();
    
            tOdd.join();
            tEven.join();
    
            System.out.println();
            System.out.println("Done!!!");
        }       
    
    }
    

以下は出力です: -

Start!!!

Odd Thread - 1
Even Thread - 2
Odd Thread - 3
Even Thread - 4
Odd Thread - 5
Even Thread - 6
Odd Thread - 7
Even Thread - 8
Odd Thread - 9
Even Thread - 10
Odd Thread - 11
Even Thread - 12
Odd Thread - 13
Even Thread - 14
Odd Thread - 15
Even Thread - 16
Odd Thread - 17
Even Thread - 18
Odd Thread - 19
Even Thread - 20

Done!!!
于 2016-02-10T08:28:15.137 に答える
0

以下の解決策は、2 つのスレッドを使用して偶数と奇数を出力するために、Java 8 Completable Future と Executor サービスを使用しています。

ExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("first");
        return t;
    });

    ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("second");
        return t;
    });

    IntStream.range(1, 101).forEach(num -> {

        CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {

            if (x % 2 == 1) {
                System.out.println(x + " " + Thread.currentThread().getName());
            }
            return num;
        }, firstExecutorService);

        thenApplyAsync.join();

        CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
            if (x % 2 == 0) {
                System.out.println(x + " " + Thread.currentThread().getName());
            }
            return num;
        }, secondExecutorService);

        thenApplyAsync2.join();
    });

    firstExecutorService.shutdown();
    secondExecutorService.shutdown();

以下はそのコンソールログです。
ここに画像の説明を入力

于 2021-08-11T12:53:16.397 に答える
0

私はこの方法でそれを行いました.2つのスレッドを使用して印刷している間、どのスレッド
が最初に実行されるかを予測することはできません
.

class Printoddeven{

    public synchronized void print(String msg) {
        try {
            if(msg.equals("Even")) {
                for(int i=0;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            } else {
                for(int i=1;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class PrintOdd extends Thread{
    Printoddeven oddeven;
    public PrintOdd(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("ODD");
    }
}

class PrintEven extends Thread{
    Printoddeven oddeven;
    public PrintEven(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("Even");
    }
}



public class mainclass 
{
    public static void main(String[] args) {
        Printoddeven obj = new Printoddeven();//only one object  
        PrintEven t1=new PrintEven(obj);  
        PrintOdd t2=new PrintOdd(obj);  
        t1.start();  
        t2.start();  
    }
}
于 2014-12-23T07:20:48.110 に答える
0

これが問題に対する私の解決策です。を実装する2つのクラスがRunnableあり、1つは奇数シーケンスを出力し、もう1つは偶数を出力します。Objectロックに使用するのインスタンスがあります。2 つのクラスを同じオブジェクトで初期化します。2 つのクラスの run メソッド内にがありsynchronized block、ループ内で、各メソッドは番号の 1 つを出力し、他のスレッドに通知し、同じオブジェクトのロックを待機してから、同じロックを再度待機します。

クラス:

public class PrintEven implements Runnable{
private Object lock;
public PrintEven(Object lock) {
    this.lock =  lock;
}
@Override
public void run() {
    synchronized (lock) {
        for (int i = 2; i <= 10; i+=2) {
            System.out.println("EVEN:="+i);
            lock.notify();
            try {
                //if(i!=10) lock.wait();
                lock.wait(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

  }
}


public class PrintOdd implements Runnable {
private Object lock;
public PrintOdd(Object lock) {
    this.lock =  lock;
}
@Override
public void run() {
    synchronized (lock) {
        for (int i = 1; i <= 10; i+=2) {
            System.out.println("ODD:="+i);
            lock.notify();
            try {
                //if(i!=9) lock.wait();
                lock.wait(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
}

public class PrintEvenOdd {
public static void main(String[] args){
    Object lock = new Object(); 
    Thread thread1 =  new Thread(new PrintOdd(lock));
    Thread thread2 =  new Thread(new PrintEven(lock));
    thread1.start();
    thread2.start();
}
}

この例の上限は 10 です。奇数スレッドが 9 を出力するか、偶数スレッドが 10 を出力すると、それ以上待機するスレッドは必要ありません。したがって、 one を使用してそれを処理できif-blockます。または、オーバーロードwait(long timeout)されたメソッドを使用して待機をタイムアウトにすることもできます。ただし、ここに 1 つの欠陥があります。このコードでは、どのスレッドが最初に実行を開始するかは保証できません。

ロックと条件を使用した別の例

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionOddEven {
 public static void main(String[] args) {
    Lock lock =  new ReentrantLock();
    Condition evenCondition = lock.newCondition();
    Condition oddCondition = lock.newCondition();
    Thread evenThread =  new Thread(new EvenPrinter(10, lock, evenCondition, oddCondition));
    Thread oddThread =  new Thread(new OddPrinter(10, lock, evenCondition, oddCondition));
    oddThread.start();
    evenThread.start();
}

static class OddPrinter implements Runnable{
    int i = 1;
    int limit;
    Lock lock;
    Condition evenCondition;
    Condition oddCondition;

    public OddPrinter(int limit) {
        super();
        this.limit = limit;
    }

    public OddPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
        super();
        this.limit = limit;
        this.lock = lock;
        this.evenCondition = evenCondition;
        this.oddCondition = oddCondition;
    }

    @Override
    public void run() {
        while( i <=limit) {
            lock.lock();
            System.out.println("Odd:"+i);
            evenCondition.signal();
            i+=2;
            try {
                oddCondition.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

static class EvenPrinter implements Runnable{
    int i = 2;
    int limit;
    Lock lock;
    Condition evenCondition;
    Condition oddCondition;

    public EvenPrinter(int limit) {
        super();
        this.limit = limit;
    }


    public EvenPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
        super();
        this.limit = limit;
        this.lock = lock;
        this.evenCondition = evenCondition;
        this.oddCondition = oddCondition;
    }


    @Override
    public void run() {
        while( i <=limit) {
            lock.lock();
            System.out.println("Even:"+i);
            i+=2;
            oddCondition.signal();
            try {
                evenCondition.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

}

于 2015-10-03T06:01:36.113 に答える
0

これは Lock と Condition を使用して実現できます。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class EvenOddThreads {

    public static void main(String[] args) throws InterruptedException {
        Printer p = new Printer();
        Thread oddThread = new Thread(new PrintThread(p,false),"Odd  :");
        Thread evenThread = new Thread(new PrintThread(p,true),"Even :");
        oddThread.start();
        evenThread.start();
    }

}

class PrintThread implements Runnable{
    Printer p;
    boolean isEven = false;

    PrintThread(Printer p, boolean isEven){
        this.p = p;
        this.isEven = isEven;
    }

    @Override
    public void run() {
        int i = (isEven==true) ? 2 : 1;
        while(i < 10 ){
            if(isEven){
                p.printEven(i);
            }else{
                p.printOdd(i);
            }
            i=i+2;
        }
    }
}

class Printer{

    boolean isEven = true;
    Lock lock = new ReentrantLock();
    Condition condEven = lock.newCondition();
    Condition condOdd = lock.newCondition();

    public void printEven(int no){
        lock.lock();
        while(isEven==true){
            try {
                condEven.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() +no);
        isEven = true;
        condOdd.signalAll();
        lock.unlock();
    }

    public void printOdd(int no){
        lock.lock();
        while(isEven==false){
            try {
                condOdd.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() +no);
        isEven = false;
        condEven.signalAll();
        lock.unlock();
    }
}
于 2016-12-30T08:54:03.637 に答える
0
package example;

public class PrintSeqTwoThreads {

    public static void main(String[] args) {
        final Object mutex = new Object();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int j = 0; j < 10;) {
                    synchronized (mutex) {
                        System.out.println(Thread.currentThread().getName() + " " + j);
                        j = j + 2;
                        mutex.notify();
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int j = 1; j < 10;) {
                    synchronized (mutex) {
                        System.out.println(Thread.currentThread().getName() + " " + j);
                        j = j + 2;
                        mutex.notify();
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        t1.start();
        t2.start();
    }
}
于 2017-05-28T11:23:51.047 に答える
0

単一クラスを使用した実用的なソリューション

package com.fursa.threads;

   public class PrintNumbers extends Thread {

     Object lock;

    PrintNumbers(Object lock) {
         this.lock = lock;
    }

    public static void main(String ar[]) {
        Object obj = new Object();
        // This constructor is required for the identification of wait/notify
        // communication
        PrintNumbers odd = new PrintNumbers(obj);
        PrintNumbers even = new PrintNumbers(obj);
        odd.setName("Odd");
        even.setName("Even");
        even.start();
        odd.start();

    }

    @Override
    public void run() {
        for(int i=0;i<=100;i++) {

            synchronized (lock) {

                if (Thread.currentThread().getName().equals("Even")) {

                    if(i % 2 == 0 ){
                        System.out.println(Thread.currentThread().getName() + " - "+ i);
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }                   
                    else if (i % 2 != 0 ) {
                        lock.notify();
                    }
                }

                if (Thread.currentThread().getName().equals("Odd")) {

                    if(i % 2 == 1 ){
                        System.out.println(Thread.currentThread().getName() + " - "+ i);
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }                   
                    else if (i % 2 != 1 ) {
                        lock.notify();
                    }
                }

            }
        }
    }
}
于 2016-08-04T09:37:02.180 に答える
-1
public class PrintOddEven {
private static class PrinterThread extends Thread {

    private static int current = 0;
    private static final Object LOCK = new Object();

    private PrinterThread(String name, int number) {
        this.name = name;
        this.number = number;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (LOCK) {
                try {
                    LOCK.wait(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (current < number) {
                    System.out.println(name + ++current);
                } else {
                    break;
                }

                LOCK.notifyAll();
            }
        }
    }

    int number;
    String name;
}

public static void main(String[] args) {
    new PrinterThread("thread1 : ", 20).start();
    new PrinterThread("thread2 : ", 20).start();
}
}
于 2014-12-09T18:47:04.173 に答える
-1

public class EvenOddex {

public static class print {

    int n;
    boolean isOdd = false;

    synchronized public void printEven(int n) {

        while (isOdd) {
            try {
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        System.out.print(Thread.currentThread().getName() + n + "\n");

        isOdd = true;
        notify();
    }

    synchronized public void printOdd(int n) {
        while (!isOdd) {
            try {
                wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(EvenOddex.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        System.out.print(Thread.currentThread().getName() + n + "\n");
        isOdd = false;
        notify();



    }
}

public static class even extends Thread {

    print po;

    even(print po) {

        this.po = po;

        new Thread(this, "Even").start();

    }

    @Override
    public void run() {


        for (int j = 0; j < 10; j++) {
            if ((j % 2) == 0) {
                po.printEven(j);
            }
        }

    }
}

public static class odd extends Thread {

    print po;

    odd(print po) {

        this.po = po;
        new Thread(this, "Odd").start();
    }

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {

            if ((i % 2) != 0) {
                po.printOdd(i);
            }
        }

    }
}

public static void main(String args[]) {
    print po = new print();
    new even(po);
    new odd(po);

}

}

于 2014-04-17T09:00:22.423 に答える
-2
import java.util.concurrent.Semaphore;


public class PrintOddAndEven {

private static class OddThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;
    private int value = 1;

    public  OddThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire odd semaphore
                semaphore.acquire();
                System.out.println(" Odd Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


private static class EvenThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;

    private int value = 2;

    public  EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire even semaphore
                semaphore.acquire();
                System.out.println(" Even Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


public static void main(String[] args) {
    //Initialize oddSemaphore with permit 1
    Semaphore oddSemaphore = new Semaphore(1);
    //Initialize evenSempahore with permit 0
    Semaphore evenSempahore = new Semaphore(0);
    OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);
    EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);
    oddThread.start();
    evenThread.start();
    }
}
于 2016-04-15T06:18:48.960 に答える