Ordering threads to run in the order they were created/started

前端 未结 10 1209
礼貌的吻别
礼貌的吻别 2020-11-30 06:15

How can i order threads in the order they were instantiated.e.g. how can i make the below program print the numbers 1...10 in order.

public class ThreadOrder         


        
10条回答
  •  情歌与酒
    2020-11-30 06:57

    This can be done without using synchronized keyword and with the help of volatile keyword. Following is the code.

    package threadOrderingVolatile;
    
    public class Solution {
        static volatile int counter = 0;
        static int print = 1;
        static char c = 'A';
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Thread[] ths = new Thread[4];
            for (int i = 0; i < ths.length; i++) {
                ths[i] = new Thread(new MyRunnable(i, ths.length));
                ths[i].start();
            }
        }
    
        static class MyRunnable implements Runnable {
            final int thID;
            final int total;
    
            public MyRunnable(int id, int total) {
                thID = id;
                this.total = total;
            }
    
            @Override
            public void run() {
                while(true) {
                    if (thID == (counter%total)) {
                        System.out.println("thread " + thID + " prints " + c);
                        if(c=='Z'){
                            c='A';
                        }else{
                            c=(char)((int)c+1);
                        }
                        System.out.println("thread " + thID + " prints " + print++);
                        counter++;                  
                    } else {
                        try {
                            Thread.sleep(30);
                        } catch (InterruptedException e) {
                            // log it
                        }
                    }
                }
            }
    
        }
    
    }
    

    Following is the github link which has a readme, that gives detailed explanation about how it happens. https://github.com/sankar4git/volatile_thread_ordering

提交回复
热议问题