1 year ago

#362786

test-img

user18658416

How can scheduleAtFixedRate run with just 1 thread?

I created a schedule work with scheduleAtFixedRate, and the thread I set 2 ways to execute, 1、

  1. Thread.sleep(10000);
  2. Thread.sleep(200);

when I run this code, it will execute with a 2s delay, but when a==3, the thread sleep 10s, and then, there will exclude 5 thread immediately, How can I just run 1 thread but not 5?

public class Words {
    private int a =0;

    public void init(){
        ScheduledExecutorService executor   = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                Date d = new Date();
                SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                System.out.println(sbf.format(d));
                try {
                    if (a == 3) {
                        Thread.sleep(10000);
                    } else {
                        Thread.sleep(200);
                    }
                    a += 1;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        Words words = new Words();
        words.init();

    }

}

enter image description here

Maybe the thread will execute very long, but I don't want the scheduleAtFixedRate to execute a lot of threads like the phenomenon I've said, How can the scheduleAtFixedRate just run 1 thread? thank you

java

multithreading

schedule

0 Answers

Your Answer

Accepted video resources