Create two threads, one display odd & other even n

2020-02-08 05:57发布

I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?

public class Mythread {

    public static void main(String[] args) {
        Runnable r = new Runnable1();
        Thread t = new Thread(r);
        t.start();
        Runnable r2 = new Runnable2();
        Thread t2 = new Thread(r2);
        t2.start();
    }
}

class Runnable2 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 1)
                System.out.println(i);
        }
    }
}

class Runnable1 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 0)
                System.out.println(i);
        }
    }
}

20条回答
萌系小妹纸
2楼-- · 2020-02-08 06:38
package thread;

import org.hibernate.annotations.Synchronize;

class PrintOdd implements Runnable {
    int count = -1;
    private Object common;

    PrintOdd(Object common) {
        this.common = common;
    }

    @Override
    public void run() {
        synchronized (common) {
            while (count < 1000) {
                try {
                    common.notifyAll();
                    System.out.println(count += 2);
                    common.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

class PrintEven implements Runnable {

    int count = 0;
    private Object common;

    PrintEven(Object common) {
        this.common = common;
    }

    @Override
    public void run() {
        synchronized (common) {
            while (count < 1000) {
                try {
                    common.notifyAll();
                    System.out.println(count += 2);
                    common.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

public class PrintNatural {
    public static void main(String args[]) {
        Object obj = new Object();
        Runnable r = new PrintOdd(obj);
        Thread printOdd = new Thread(r);

        Runnable r2 = new PrintEven(obj);
        Thread printEven = new Thread(r2);

        printOdd.start();
        printEven.start();

    }

}
查看更多
Bombasti
3楼-- · 2020-02-08 06:38

Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.

public class ThreadingOddEvenNumbers {

    void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(57);
        Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter");
        Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter");
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}

class MyRunner implements Runnable {
    private Printer p;
    private boolean evenProperty;

    public MyRunner(Printer p, boolean evenNess) {
        this.p = p;
        evenProperty = evenNess;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            System.out.println(this.getClass().getName() + " "
                    + ex.getMessage());
        }
    }


    public void print() throws InterruptedException {
        while (!p.isJobComplete()) {
            synchronized (p) {
                if (evenProperty)
                    while (p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
                else
                    while (!p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
            }

            synchronized (p) {
                if (evenProperty)
                    p.printEven(Thread.currentThread().getName());
                else
                    p.printOdd(Thread.currentThread().getName());
                p.notifyAll();
                System.out.println("notify called: by: "
                        + Thread.currentThread().getName());
            }
        }
    }
}

class Printer {
    private volatile boolean evenPrinted;
    private volatile boolean jobComplete;
    private int limit;
    private int counter;

    public Printer(int lim) {
        limit = lim;
        counter = 1;
        evenPrinted = true;
        jobComplete = false;
    }

    public void printEven(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = true;
    }

    public void printOdd(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = false;
    }

    private void incrCounter() {
        counter++;
        if (counter >= limit)
            jobComplete = true;
    }

    public int getLimit() {
        return limit;
    }

    public boolean isEvenPrinted() {
        return evenPrinted;
    }

    public boolean isJobComplete() {
        return jobComplete;
    }
}
查看更多
Evening l夕情丶
4楼-- · 2020-02-08 06:38
public class EvenOddNumberPrintUsingTwoThreads {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Thread t1 = new Thread() {          
            public void run() {

                for (int i = 0; i <= 10; i++) {
                    if (i % 2 == 0) {
                        System.out.println("Even : " + i);
                    }
                }

            }
        };

        Thread t2 = new Thread() {
            // int i=0;
            public void run() {

                for (int i = 0; i <= 10; i++) {
                    if (i % 2 == 1) {
                        System.out.println("Odd : " + i);
                    }
                }

            }
        };
        t1.start();
        t2.start();
    }
}
查看更多
神经病院院长
5楼-- · 2020-02-08 06:39

Below is the code which uses lock on a shared object which has the number to be printed. It guarantees the sequence also unlike the above solution.

public class MultiThreadPrintNumber {
  int i = 1;

  public synchronized void printNumber(String threadNm) throws InterruptedException{

      if(threadNm.equals("t1")){
        if(i%2 == 1){
          System.out.println(Thread.currentThread().getName()+"--"+ i++);
          notify();
        } else {
          wait();
        }
      } else if(threadNm.equals("t2")){
        if(i%2 == 0){
          System.out.println(Thread.currentThread().getName()+"--"+ i++);
          notify();
        } else {
          wait();
        }
      }

    }

  public static void main(String[] args) {
    final MultiThreadPrintNumber obj = new MultiThreadPrintNumber();
    Thread t1 = new Thread(new Runnable() {

      @Override
      public void run() {
        try {
          while(obj.i <= 10){

            obj.printNumber(Thread.currentThread().getName());
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("done t1");
      }
    });
    Thread t2 = new Thread(new Runnable() {

      @Override
      public void run() {
        try {
          while(obj.i <=10){
            obj.printNumber(Thread.currentThread().getName());
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("done t2");
      }
    });

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

The output will look like: t1--1 t2--2 t1--3 t2--4 t1--5 t2--6 t1--7 t2--8 t1--9 t2--10 done t2 done t1

查看更多
smile是对你的礼貌
6楼-- · 2020-02-08 06:40

Concurrent Package:

    import java.util.concurrent.ExecutorService;

    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    //=========== Task1 class prints odd =====
    class TaskClass1 implements Runnable
    {

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    int i;
    TaskClass1(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        try
        {
            lock.lock();
            for(i = 1;i<11;i++)
            {
                if(i%2 == 0)
                {
                    condition.signal();
                    condition.await();

                }
                if(i%2 != 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();
        }

    }

}
//==== Task2 : prints even =======
class TaskClass2 implements Runnable
{

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    TaskClass2(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        int i;
        // TODO Auto-generated method stub
        try
        {
            lock.lock();
            for(i = 2;i<11;i++)

            {

                if(i%2 != 0)
                {
                    condition.signal();
                    condition.await();
                }
                if(i%2 == 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();

        }

    }

}
public class OddEven {

    public static void main(String[] a)
    {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Future future1;
        Future future2;
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        future1 = executorService.submit(new TaskClass1(condition,lock));
        future2 = executorService.submit(new TaskClass2(condition,lock));
        executorService.shutdown();


    }


}
查看更多
7楼-- · 2020-02-08 06:43

@aymeric answer wont print the numbers in their natural order, but this code will. Explanation at the end.

public class Driver {
    static Object lock = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {

                for (int itr = 1; itr < 51; itr = itr + 2) {
                    synchronized (lock) {
                        System.out.print(" " + itr);
                        try {
                            lock.notify();
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {

                for (int itr = 2; itr < 51; itr = itr + 2) {
                    synchronized (lock) {
                        System.out.print(" " + itr);
                        try {
                            lock.notify();
                            if(itr==50)
                                break;
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        try {
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            System.out.println("\nPrinting over");
        } catch (Exception e) {

        }
    }
}

In order to achieve so, the run methods of the two threads above have to be called one after the other, i.e. they need to be synchronized and I am achieving that using locks.

The code works like this: t1.run prints the odd number and notifies any waiting thread that it is going to release the lock, then goes into a wait state.

At this point t2.run is invoked, it prints the next even number, notifies other threads that it is about to release the lock it holds and then goes into wait state.

This continues till the itr in t2.run() reaches 50, at this point our goal has been achieved and we need to kill these two threads.

By breaking, I avoid calling lock.wait() in t2.run and t2 thread is thus shutdown, the control will now go to t1.run since it was waiting to acquire the lock; but here itr value will be > 51 and we will come out of its run(), thus shutting down the thread.

If break is not used in t2.run(), though we will see numbers 1 to 50 on the screen but the two threads will get into a deadlock situation and continue to be in wait state.

查看更多
登录 后发表回答