Friday, July 4, 2014

MULTITHREADING CHAT APPLICATION

MULTITHREADING CHAT APPLICATION


you can create a chat application using this multithreading concept


class Chat {
        boolean flag = false;

        public synchronized void Question(String msg) {
            if (flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(msg);
            flag = true;
            notify();
        }

        public synchronized void Answer(String msg) {
            if (!flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(msg);
            flag = false;
            notify();
        }
    }

    class T1 implements Runnable {
        Chat m;
        String[] s1 = { "Hi", "How are you ?", "I am also doing fine!",
                "what do you like the most?",
                "who is ur favourite actor?",
                "which is ur favourite holiday spot?",
                "what is ur favourite wish?"};

        public T1(Chat m1) {
            this.m = m1;
            new Thread(this, "Question").start();
        }

        public void run() {
            for (int i = 0; i < s1.length; i++) {
                m.Question(s1[i]);
            }
        }
    }

    class T2 implements Runnable {
        Chat m;
        String[] s2 = { "Hi", "I am good, what about you?",
                "Great!",
                "I like watching cricket",
                "my favourite actor is hrithik roshan",
                "my favourite holiday spot is paris",
                "my wish is to achieve a best employee award."};

        public T2(Chat m2) {
            this.m = m2;
            new Thread(this, "Answer").start();
        }

        public void run() {
            for (int i = 0; i < s2.length; i++) {
                m.Answer(s2[i]);
            }
        }
    }
    public class TestThread {
        public static void main(String[] args) {
            Chat m = new Chat();
            new T1(m);
            new T2(m);
        }
    }

No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...