简体   繁体   English

在 2 个线程的帮助下打印自然序列(1 个打印偶数,2'nd 打印奇数)

[英]Print Natural Sequence with help of 2 threads(1 is printing even and 2'nd is printing odd)

I have tired this question, and i ended up with some doubts.我已经厌倦了这个问题,最终我产生了一些疑问。 Please help me out请帮帮我

Doubt : If any thread is in wait state , and no other thread is notifying that one , so will it never come to and end ?怀疑:如果任何线程处于等待状态,并且没有其他线程通知该线程,那么它永远不会结束吗? Even after using wait(long milliseconds).即使在使用等待(长毫秒)之后。

For Code : What my requirement is from the code(Please Refer My Code) :对于代码:我的要求来自代码(请参阅我的代码):

a : Should print "Even Thread Finish " and "Odd Thread Finish" (Order is not imp , but must print both) a : 应该打印“Even Thread Finish”和“Odd Thread Finish”(订单不是 imp ,但必须同时打印)

b: Also in main function should print " Exit Main Thread" b: 同样在主函数中应该打印“退出主线程”

What is actually happening : After lot of runs , in some cases , it prints "Even Thread Finish" then hangs here or vice-versa.实际发生的情况:经过多次运行,在某些情况下,它会打印“Even Thread Finish”,然后挂在这里,反之亦然。 In some cases it prints both.在某些情况下,它会同时打印两者。

Also it never prints "Exit Main Thread".它也从不打印“退出主线程”。

So How to modify code , so it must print all 3 statement .(Of Course "Exit Main.. " in last , as i am using join for main.)那么如何修改代码,所以它必须打印所有 3 条语句。(当然“退出 Main..”最后,因为我使用 join 作为 main。)

In brief : Main start-> t1 start -> t2 start ,, then i need t2/t1 finish -> main finish.简而言之:主要开始-> t1 开始-> t2 开始,然后我需要t2/t1 完成-> 主要完成。

Please help me out for this problem请帮我解决这个问题

Here is my code :这是我的代码:

import javax.sql.CommonDataSource;

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Share commonObj = new Share();

        Thread even = new Thread(new EvenThread(commonObj));

        Thread odd = new Thread(new OddThread(commonObj));

        even.start();

        odd.start();

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Exit Main Thread");

    }

}

class EvenThread implements Runnable {

    private Share commShare;
    public EvenThread(Share obj) {
        // TODO Auto-generated constructor stub
        this.commShare = obj;
    }

    private int number = 2;

    public void run() {
        System.out.println("Even Thread start");
        while (number <= 50) {
            if (commShare.flag == true) {
                System.out.println("Even Thread" + number);
                number += 2;
                commShare.flag = false;
                synchronized(commShare) {
                    try {
                        commShare.notify();
                        commShare.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    commShare.notify();
                }

            } else {
                synchronized(commShare) {
                    try {
                        commShare.notify();
                        commShare.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    commShare.notify();
                }
            }

        }

        System.out.println("Even Thread Finish");
    }
}


class OddThread implements Runnable {

    private int number = 1;
    private Share commShare;


    public OddThread(Share obj) {
        // TODO Auto-generated constructor stub
        this.commShare = obj;
    }



    public void run() {
        System.out.println("Odd Thread start");
        while (number <= 50) {
            if (commShare.flag == false) {
                System.out.println("Odd Thread :" + number);
                number += 2;
                commShare.flag = true;
                synchronized(commShare) {
                    try {
                        commShare.notify();
                        commShare.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    commShare.notify();
                }
            }
        }
        System.out.println("Odd Thread Finish");
    }
}

class Share {

    Share sharedObj;
    public boolean flag = false;
}

Although this is not the exact answer of your question, but this implementation is an alternative of your problem .虽然这不是您问题的确切答案,但此实现是您问题的替代方案。

public class EvenOddThreads {
    public static void main(String[] args) {
        Thread odd = new Thread(new OddThread(), "oddThread");

        Thread even = new Thread(new EvenThread(), "Even Thread");

        odd.start();
        even.start();
        try {
            odd.join();
            even.join();
            System.out.println("Main thread exited");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
class OddThread implements Runnable{
    public void run() {
        synchronized (CommonUtil.mLock) {
            System.out.println(Thread.currentThread().getName()+"---> job starting");
            int i = 1;
            while(i<50){
                System.out.print(i + "\t");
                i = i + 2;
                CommonUtil.mLock.notify();
                try {
                    CommonUtil.mLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("OddThread---> job completed");
            CommonUtil.mLock.notify();

        }
    }
}

class EvenThread implements Runnable{
    @Override
    public void run() {
        synchronized (CommonUtil.mLock) {
            System.out.println(Thread.currentThread().getName()+"---> job started");
            int i =2;
            while(i<50){
                System.out.print(i + "\t");
                i = i+2;
                CommonUtil.mLock.notify();
                try {
                    CommonUtil.mLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("EvenThread---> job completed");
            CommonUtil.mLock.notify();
        }
    }
}

class CommonUtil{
    static final Object mLock= new Object();
}

Output:输出:

oddThread---> job starting
1   Even Thread---> job started
2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  EvenThread---> job completed
OddThread---> job completed
Main thread exited

Well, I have spent last three hours reading a Java sychronization tutorial (a very good one) followed by more info about wait, notify and notifyAll , and i ended up with program that uses N threads to count from A to B, set N to 2 and you have odd and even.好吧,我花了三个小时阅读Java 同步教程(非常好的教程),然后阅读了有关wait、notify 和 notifyAll的更多信息,最后我得到了使用 N 个线程从 A 到 B 计数的程序,将 N 设置为2 你有奇数和偶数。

pastebin粘贴箱

Also, my program has no comments whatsoever, so make sure you read the tutorial(s) before you try understand this code.此外,我的程序没有任何注释,因此在尝试理解此代码之前,请务必阅读教程。

This could be an exercise on threads and lock monitors, but there is nothing to do in parallel that give you advantages.这可能是关于线程和锁监视器的练习,但没有任何并行可以给您带来好处。

In your code when a thread 1 (OddThread or EvenThread) ends his work and prints out "Odd Thread Finish" (or "Even Thread Finish") the other thread 2 is waiting a notify() or a notifyAll() that never will happen because the first is over.在您的代码中,当线程 1(OddThread 或 EvenThread)结束其工作并打印出“Odd Thread Finish”(或“Even Thread Finish”)时,另一个线程 2 正在等待一个永远不会发生的 notify() 或 notifyAll()因为第一次结束了。

You have to change EvenThread and OddThread adding a synchronized block with a notify call on commShare just after the while cycle.您必须更改 EvenThread 和 OddThread,在 while 循环之后添加一个同步块,并在 commShare 上调用通知。 I removed the second if-branch because in this way you don't continue to check the while condition but get a wait on commShare soon.我删除了第二个 if 分支,因为通过这种方式,您不会继续检查 while 条件,但很快就会等待 commShare。

class EvenThread implements Runnable {
    private Share commShare;
    private int number = 2;

    public EvenThread(Share obj) {
        this.commShare = obj;
    }
    public void run() {
        System.out.println("Even Thread start");
        while (number <= 50) {
            synchronized (commShare) {
                if (commShare.flag) {
                    System.out.println("Even Thread:" + number);
                    number += 2;
                    commShare.flag = false;
                }
                commShare.notify();
                try {
                    commShare.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        synchronized (commShare) {
            commShare.notify();
            System.out.println("Even Thread Finish");
        }
    }
}

class OddThread implements Runnable {
    private int number = 1;
    private Share commShare;

    public OddThread(Share obj) {
        this.commShare = obj;
    }
    public void run() {
        System.out.println("Odd Thread start");
        while (number <= 50) {
            synchronized (commShare) {
                if (!commShare.flag) {
                    System.out.println("Odd Thread: " + number);
                    number += 2;
                    commShare.flag = true;
                }
                commShare.notify();
                try {
                    commShare.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
        synchronized (commShare) {
            commShare.notify();
            System.out.println("Odd Thread Finish");
        }
    }

Finally, in the main you have to join for each thread you started.最后,总的来说,您必须为您启动的每个线程加入。 It's sure that Thread.currentThread() returns just one of yours threads?确定 Thread.currentThread() 只返回您的线程之一吗? We have started two threads and those threads we should join.我们已经启动了两个线程,我们应该加入这些线程。

try {
      even.join();
      odd.join();
} catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
}

Also it never prints "Exit Main Thread".它也从不打印“退出主线程”。

That is because maybe because your threads are waiting on the lock for someone to notify() but due to missed signal or no one signalling them, they never get out of waiting state.那是因为可能是因为您的线程正在等待某人notify()的锁,但由于错过了信号或没有人向他们发出信号,他们永远不会退出等待状态。 For that the best solution is to use:为此,最好的解决方案是使用:

public final void wait(long timeout)
                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.导致当前线程等待,直到另一个线程为此对象调用notify()方法或notifyAll()方法,或者指定的时间量已经过去。

This overloaded method will wait for other thread to notify for specific amount of time and then return if timeout occurs.此重载方法将等待其他线程通知特定时间,然后在超时发生时返回。 So in case of a missed signal the thread will still resume its work.因此,在丢失信号的情况下,线程仍将恢复其工作。

NOTE: After returning from wait state always check for PRE-CONDITION again, as it can be a Spurious Wakeup .注意:从等待状态返回后,始终再次检查PRE-CONDITION ,因为它可能是Spurious Wakeup

Here is my flavor of program that I coded some time back for the same.这是我一段时间以前编写的程序风格。

import java.util.concurrent.atomic.AtomicInteger;


public class Main {

    private static int range = 10;
    private static volatile AtomicInteger present = new AtomicInteger(0);
    private static Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new OddRunnable()).start();
        new Thread(new EvenRunnable()).start();
    }

    static class OddRunnable implements Runnable{

        @Override
        public void run() {
            while(present.get() <= range){
                if((present.get() % 2) != 0){
                    System.out.println(present.get());
                    present.incrementAndGet();
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }else{
                    synchronized (lock) {
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            }
        }
    }

    static class EvenRunnable implements Runnable{

        @Override
        public void run() {
            while(present.get() <= range){
                if((present.get() % 2) == 0){
                    System.out.println(present.get());
                    present.incrementAndGet();
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }else{
                    synchronized (lock) {
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            }
        }
    }
}

See the solution, I have kept a lock that works for notifying the chance of even or odd thread.查看解决方案,我保留了一个lock ,用于通知偶数或奇数线程的机会。 If even thread finds that the present number is not even it waits on the lock and hopes that odd thread will notify it when it prints that odd number.如果偶数线程发现当前的数字不是偶数,它就等待lock并希望奇数线程在打印该奇数时通知它。 And similarly it works for odd thread too.同样,它也适用于奇数线程。

I am not suggesting that this is the best solution but this is something that came out in the first try, some other options are also possible.我并不是说这是最好的解决方案,但这是第一次尝试的结果,其他一些选择也是可能的。

Also I would like to point out that this question though as a practice is good, but do keep in mind that you are not doing anything parallel there.另外我想指出,这个问题虽然作为一种实践是好的,但请记住,你没有在那里做任何平行的事情。

I will not vote for using wait() and notify().我不会投票支持使用wait()notify(). The things that you can do with wait and notify can be done through more sophisticated tools like semaphore , countDownLatch , CyclicBarrier .您可以通过更复杂的工具(如semaphorecountDownLatchCyclicBarrier完成waitnotify操作。 You can find this advice in the famous book Effective java in item number 69 prefer concurrency utilities to wait and notify .您可以在著名书籍 Effective java 的第 69 项中找到此建议, 更喜欢并发实用程序等待和通知

Even in this case we don't need this things at all, we can achieve this functionality by a simple volatile boolean variable.即使在这种情况下我们根本不需要这些东西,我们可以通过一个简单的volatile boolean变量来实现这个功能。 And for stopping a thread the best possible way is to use interrupt .对于停止线程,最好的方法是使用interrupt After certain amount of time or some predefined condition we can interrupt threads.在一定的时间或一些预定义的条件之后,我们可以中断线程。 Please find my implementation attached:请附上我的实现:

Thread 1 for printing even numbers:用于打印偶数的线程 1:

public class MyRunnable1 implements Runnable
{
    public static volatile boolean isRun = false;
    private int k = 0 ;
    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            if(isRun){
                System.out.println(k);
                k+=2;
                isRun=false;
                MyRunnable2.isRun=true;
            }
        }
    }
}

Thread 2 for printing even numbers:用于打印偶数的线程 2:

public class MyRunnable2 implements Runnable{
    public static volatile boolean isRun = false;
    private int k = 1 ;
    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            if(isRun){
                System.out.println(k);
                k+=2;
                isRun=false;
                MyRunnable1.isRun=true;
            }
        }
    }
}

Now main method which drives the above threads现在驱动上述线程的主要方法

public class MyMain{
    public static void main(String[] args) throws InterruptedException{
        Thread t1 = new Thread(new MyRunnable1());
        Thread t2 = new Thread(new MyRunnable2());
        MyRunnable1.isRun=true;
        t1.start();
        t2.start();
        Thread.currentThread().sleep(1000);
        t1.interrupt();
        t2.interrupt();
    }
}

There may be some places you need to change a bit this is just a skeletal implementation.可能有些地方你需要稍微改变一下,这只是一个骨架实现。 Hope it helps and please let me know if you need something else.希望它有所帮助,如果您需要其他东西,请告诉我。

public class PrintNumbers {

    public static class Condition {
        private boolean start = false;
        public boolean getStart() {
            return start;
        }

        public void setStart(boolean start) {
            this.start = start;
        }
    }

    public static void main(String[] args) {

        final Object lock = new Object();
        // condition used to start the odd number thread first
        final Condition condition = new Condition();

        Thread oddThread = new Thread(new Runnable() {
            public void run() {
                synchronized (lock) {
                    for (int i = 1; i <= 10; i = i + 2) { //For simplicity assume  only printing till 10;
                        System.out.println(i);
                        //update condition value to signify that odd number thread has printed first
                        if (condition.getStart() == false) {
                            condition.setStart(true);
                        }
                        lock.notify();
                        try {
                            if (i + 2 <= 10) { 
                                lock.wait(); //if more numbers to print, wait;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        });

        Thread evenThread = new Thread(new Runnable() {
            public void run() {
                synchronized (lock) {
                    for (int i = 2; i <= 10; i = i + 2) { //For simplicity assume only printing till 10;
                        // if thread with odd number has not printed first, then wait
                        while (condition.getStart() == false) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println(i);
                        lock.notify();
                        try {
                            if (i + 2 <= 10) { //if more numbers to print, wait;
                                lock.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        });

        oddThread.start();
        evenThread.start();

    }

}

I did it using ReentrantLock with 25 threads .我使用 25 个线程的 ReentrantLock 做到了。 One thread Print One number and it will notify to other .一个线程打印一个数字,它会通知其他。

public class ReentrantLockHolder 
{
    private Lock lock;

    private Condition condition;

    public ReentrantLockHolder(Lock lock )
    {
        this.lock=lock;
        this.condition=this.lock.newCondition();
    }

    public Lock getLock() {
        return lock;
    }

    public void setLock(Lock lock) {
        this.lock = lock;
    }

    public Condition getCondition() {
        return condition;
    }

    public void setCondition(Condition condition) {
        this.condition = condition;
    }
}
public class PrintThreadUsingReentrantLock implements Runnable
{
    private ReentrantLockHolder currHolder;

    private ReentrantLockHolder nextHolder;

    private PrintWriter writer;

    private static int i=0;

    public PrintThreadUsingReentrantLock(ReentrantLockHolder currHolder, ReentrantLockHolder nextHolder ,PrintWriter writer)
    {
        this.currHolder=currHolder;
        this.nextHolder=nextHolder;
        this.writer=writer;
    }

    @Override
    public void run() 
    {
        while (true) 
        {
            writer.println(Thread.currentThread().getName()+ " "+ ++i);

            try{
                nextHolder.getLock().lock();
                nextHolder.getCondition().signal();
            }finally{
                nextHolder.getLock().unlock();  
            }

            try {
                currHolder.getLock().lock();
                currHolder.getCondition().await();
            }catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
            finally{
                currHolder.getLock().unlock();
            }
        }
    }
}
public static void main(String[] args) 
    {
        PrintWriter printWriter =null;
        try {
                printWriter=new PrintWriter(new FileOutputStream(new File("D://myFile.txt")));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ReentrantLockHolder obj[]=new ReentrantLockHolder[25];
        for(int i=0;i<25;i++)
        {
            obj[i]=new ReentrantLockHolder(new ReentrantLock());
        }

        for(int i=0;i<25;i++)
        {
            Thread t1=new Thread(new PrintThreadUsingReentrantLock(obj[i], obj[i+1 == 25 ? 0 : i+1],printWriter ),"T"+i );
            t1.start();
        }
    }

I tried the similar stuff where Thread 1 prints Odd numbers and Thread 2 prints even numbers in a correct order and also when the printing is over, the desired messages as you had suggested will be printed.我尝试了类似的东西,其中线程 1 打印奇数,线程 2 以正确的顺序打印偶数,并且当打印结束时,将打印您建议的所需消息。 Please have a look at this code请看一下这段代码

package practice;


class Test {

  private static boolean oddFlag = true;
  int count = 1;

  private void oddPrinter() {
    synchronized (this) {
      while(true) {
        try {
          if(count < 10) {
            if(oddFlag) {
              Thread.sleep(500);
              System.out.println(Thread.currentThread().getName() + ": " + count++);
              oddFlag = !oddFlag;
              notifyAll();
            }
            else {
              wait();
            }
          }
          else {
            System.out.println("Odd Thread finished");
            notify();
            break;
          }
        }
        catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  private void evenPrinter() {
    synchronized (this) {
      while (true) {
        try {
          if(count < 10) {
            if(!oddFlag) {
              Thread.sleep(500);
              System.out.println(Thread.currentThread().getName() + ": " + count++);
              oddFlag = !oddFlag;
              notify();
            }
            else {
              wait();
            }
          }
          else {
            System.out.println("Even Thread finished");
            notify();
            break;
          }
        }
        catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }


  public static void main(String[] args) throws InterruptedException{
    final Test test = new Test();

    Thread t1 = new Thread(new Runnable() {
      public void run() {
        test.oddPrinter();
      }
    }, "Thread 1");

    Thread t2 = new Thread(new Runnable() {
      public void run() {
        test.evenPrinter();
      }
    }, "Thread 2");

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

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

    System.out.println("Main thread finished");
  }
}
package test;

public class Interview2 {

public static void main(String[] args) {
    Obj obj = new Obj();

    Runnable evenThread = ()-> {
        synchronized (obj) {
            for(int i=2;i<=50;i+=2) {
                while(!obj.printEven) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }                   
                }
                System.out.println(i);
                obj.printEven = false;
                obj.notify();
            }
        }           
    };
    Runnable oddThread = ()-> {
        synchronized (obj) {
            for(int i=1;i<=49;i+=2) {
                while(obj.printEven) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }                   
                }
                System.out.println(i);
                obj.printEven = true;
                obj.notify();
            }
        }
    };      
    new Thread(evenThread).start();
    new Thread(oddThread).start();
   }
}
class Obj {
  boolean printEven;
}

This is very generic solution.这是非常通用的解决方案。 It uses semaphores to do signaling among threads.它使用信号量在线程之间进行信号传递。 This is general solution where N threads prints M natural numbers in sequence turn by turn.这是 N 个线程依次依次打印 M 个自然数的通用解决方案。 that is if we have 3 threads and we want to print 7 natural numbers, output would be:也就是说,如果我们有 3 个线程并且我们想要打印 7 个自然数,输出将是:

Thread 1 : 1主题 1 : 1

Thread 2 : 2主题 2 : 2

Thread 3 : 3主题 3 : 3

Thread 1 : 4主题 1 : 4

Thread 2 : 5主题 2 : 5

Thread 3 : 6主题 3 : 6

Thread 1 : 7主题 1 : 7

import java.util.concurrent.Semaphore;

/*
 * Logic is based on simple idea
 * each thread should wait for previous thread and then notify next thread in circular fashion
* There is no locking required
* Semaphores will do the signaling work among threads.
*/

public class NThreadsMNaturalNumbers {

private static volatile int nextNumberToPrint = 1;
private static int MaxNumberToPrint;

public static void main(String[] args) {

    int numberOfThreads = 2;
    MaxNumberToPrint = 50;

    Semaphore s[] = new Semaphore[numberOfThreads];

    // initialize Semaphores
    for (int i = 0; i < numberOfThreads; i++) {
        s[i] = new Semaphore(0);
    }

    // Create threads and initialize which thread they wait for and notify to
    for (int i = 1; i <= numberOfThreads; i++) {
        new Thread(new NumberPrinter("Thread " + i, s[i - 1], s[i % numberOfThreads])).start();
    }
    s[0].release();// So that First Thread can start Processing
}

private static class NumberPrinter implements Runnable {

    private final Semaphore waitFor;
    private final Semaphore notifyTo;
    private final String name;

    public NumberPrinter(String name, Semaphore waitFor, Semaphore notifyTo) {
        this.waitFor = waitFor;
        this.notifyTo = notifyTo;
        this.name = name;
    }

    @Override
    public void run() {

        while (NThreadsMNaturalNumbers.nextNumberToPrint <= NThreadsMNaturalNumbers.MaxNumberToPrint) {
            waitFor.acquireUninterruptibly();
            if (NThreadsMNaturalNumbers.nextNumberToPrint <= NThreadsMNaturalNumbers.MaxNumberToPrint) {
                System.out.println(name + " : " + NThreadsMNaturalNumbers.nextNumberToPrint++);
                notifyTo.release();
            }

        }
        notifyTo.release();
    }

}

} }

This Class prints Even Number:这个类打印偶数:

public class EvenThreadDetails extends Thread{

    int countNumber;
     public EvenThreadDetails(int countNumber) {
        this.countNumber=countNumber;
    }
    @Override
    public void run()
    {
        for (int i = 0; i < countNumber; i++) {
            if(i%2==0)
            {
                System.out.println("Even Number :"+i);
            }
            try {
                Thread.sleep(2);
            } catch (InterruptedException ex) {
                // code to resume or terminate...
            }
        }
    }
}

    

This Class prints Odd Numbers:这个类打印奇数:

public class OddThreadDetails extends Thread {

    int countNumber;
     public OddThreadDetails(int countNumber) {
        this.countNumber=countNumber;
    }
    @Override
    public void run()
    {
        for (int i = 0; i < countNumber; i++) {
            if(i%2!=0)
            {
                System.out.println("Odd Number :"+i);
            }
            try {
                Thread.sleep(2);
            } catch (InterruptedException ex) {
                // code to resume or terminate...
            }       
        }
    }
}

This is Main class:这是主类:

public class EvenOddDemo {

    public static void main(String[] args) throws InterruptedException
    {
        Thread eventhread= new EvenThreadDetails(100);
        Thread oddhread=new OddThreadDetails(100);
        eventhread.start();
        oddhread.start();   
    }
}
I have done it this way and its working...

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();  

}
}
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();
                        }
                    }
                }
                System.out.println("\nEven Thread Finish ");
            }
        });
        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();
                        }
                    }
                }
                System.out.println("\nOdd Thread Finish ");
            }
        });
        try {
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            System.out.println("Exit Main Thread");
        } catch (Exception e) {

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM