creating threads through annomyous inner class

后端 未结 3 895
情深已故
情深已故 2021-02-10 09:25

I was developing the code of creating a thread but without extending the thread class or implementing the runnable interface , that is through anonymous inner classes ..

3条回答
  •  春和景丽
    2021-02-10 09:50

     Runnable run = new Runnable() {
        public void run() {
            try {
                for (int i = 0; i < 20; i++) {
                    Thread.sleep(1000);
                    System.out.print(i + "\n" + "..");
                }
    
            } catch (InterruptedException e) {
                System.out.println(" interrupted");
            }
        }
     };
     new Thread(run).start();
     new Thread(run).start();
    

    Don't wait for one to finish before starting the second or you have three threads where on one is ever running (in which case the additional threads were pointless)

    BTW: Your synchronized isn't doing anything useful but it could cause the Thread to function incorrectly.


提交回复
热议问题