Using multiple threads to print statements sequentially

强颜欢笑 提交于 2019-12-01 10:54:37
Kalyan Chakravarthi

Please see my solution here..

Using simple wait/notify https://stackoverflow.com/a/31668619/1044396

Using cyclic barriers: https://stackoverflow.com/a/23752952/1044396

For your query on 'How different it is from even/odd thread problem. --> it is almost same ... instead of maintaining two states have one more state to call the third thread, so I believe,this can be extended any number of threads.

EDIT:

You may view this approach when you want to have 'n' number of threads to do the work sequentially.(Instead of having different classes t1,t2,t3 etc)

https://codereview.stackexchange.com/a/98305/78940

EDIT2: Copying the code here again for the above solution

I tried to solve using a single class 'Thrd' which gets initialized with its starting number.

ThreadConfig class which as size of total number of threads you want to create.

State class which maintains the state of the previous thread.(to maintain ordering)

Here you go..(please review and let me know your views)

EDIT: How it works -->

when a thread Tx gets a chance to execute.. it will set state variable's state with x. So a next thread(Tx+1) waiting , will get a chance once state gets updated. This way you can maintain the ordering of threads.

I hope i am able to explain the code. Please run it and see or let me know for any specific queries on the below code

1) package com.kalyan.concurrency;

    public class ThreadConfig {

        public static final int size = 5;

    }

2) package com.kalyan.concurrency;

    public class State {

      private volatile int state ;

        public State() {
            this.state =3;
        }

        public State(int state) {
            this.state = state;
        }

        public  int getState() {
            return state;
        }

        public  void setState(int state) {
            this.state = state;
        }


    }

3) package com.kalyan.concurrency;

        public class Thrd implements Runnable {

            int i ;
            int name;
            int prevThread;
            State s;
            public Thrd(int i,State s) {
                this.i=i;
                this.name=i;
                this.prevThread=i-1;
                if(prevThread == 0) prevThread=ThreadConfig.size;
                this.s=s;
            }

            @Override
            public void run() {


                while(i<50)
                {
                    synchronized(s)
                      {
                          while(s.getState() != prevThread)
                          {


                                  try {
                                    s.wait();
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                              }

                          } 

                              synchronized(s)
                              {
                               //if(s.getState() ==3)

                              if(s.getState()==prevThread)
                               System.out.println("t"+ name+ i);
                               s.setState(name);
                                   i = i +ThreadConfig.size ;
                              s.notifyAll();


                             }   
                }

            }

        }

4) package com.kalyan.concurrency;

        public class T1t2t3 {
        public static void main(String[] args) {

            State s = new State(ThreadConfig.size);


            for(int i=1;i<=ThreadConfig.size;i++)
            {
                Thread T = new Thread(new Thrd(i,s));   
                T.start();

            }



        }
        }

OUTPUT:

 t11
 t22
 t33
 t44
 t55
 t16
 t27
 t38
 t49
 t510
 t111
 t212
 t313
 t414
 t515
 t116..............
superfuzzy

I hope I understood you right, but there are to main "features" in java to make a variable being shared between threads:

  • the volatile keyword

    volatile int number = 1;

  • AtomicInteger (a standard java class -> no library)

    AtomicInteger number = new AtomicInteger(1);

These two techniques should both do what you want, however I have no experience using it, I just came upon this word, didn't know what it means and did some digging.

Some stuff to read: ;)

volatile for java explained --> http://java.dzone.com/articles/java-volatile-keyword-0

a better explanation (with IMAGES!!) but for c# (which is still the same usage) --> http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

And a link to some usages of AtomicInteger --> https://stackoverflow.com/a/4818753/4986655

I hope I could help you or at least send you in the right direction :)
- superfuzzy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!