在 2 个线程的帮助下打印自然序列(1 个打印偶数,2'nd 打印奇数) [英] Print Natural Sequence with help of 2 threads(1 is printing even and 2'nd is printing odd)

查看:51
本文介绍了在 2 个线程的帮助下打印自然序列(1 个打印偶数,2'nd 打印奇数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经厌倦了这个问题,最终我产生了一些疑问.请帮帮我

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 : 应该打印Even Thread Finish"和Odd Thread Finish"(订单不是 imp ,但必须同时打印)

a : Should print "Even Thread Finish " and "Odd Thread Finish" (Order is not imp , but must print both)

b: 同样在主函数中应该打印退出主线程"

b: Also in main function should print " Exit Main Thread"

实际发生的事情:经过大量运行后,在某些情况下,它会打印Even Thread Finish"然后挂在这里,反之亦然.在某些情况下,它会同时打印.

What is actually happening : After lot of runs , in some cases , it prints "Even Thread Finish" then hangs here or vice-versa. In some cases it prints both.

它也从不打印退出主线程".

Also it never prints "Exit Main Thread".

那么如何修改代码,所以它必须打印所有 3 条语句.(当然,最后是退出 Main..",因为我在 main 中使用了 join.)

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.)

简而言之:Main start-> t1 start -> t2 start ,然后我需要t2/t1 finish -> main finish.

请帮我解决这个问题

这是我的代码:

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

输出:

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

这篇关于在 2 个线程的帮助下打印自然序列(1 个打印偶数,2'nd 打印奇数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆