Why there is only one thread can actually started in @PostConstruct method?

workplaylifecycle :
@Component
class Type
{
    @PostConstruct
    private void postConstructor() {

        Runnable threadAlpha = () -> {
            while (true) {
                workWithSomething();
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                }
            }
        };
        Runnable threadBeta = () -> {
            while (true) {
                workWithOtherthing();
                try {
                    Thread.sleep(1000 * 3);
                } catch (InterruptedException e) {
                }
            }
        };
        threadBeta.run();
        threadAlpha.run();
    }
}

With spring-framework, I am struggling with this piece of code, the problem is only one thread can actually started which call run() first, the other one seems freezing, If I switch the location to be like:

        threadAlpha.run();
        threadBeta.run();

Then threadBeta never started, why something happen like that?

youhans :

Because you're not creating threads. Instead of that you're creating Runnable instances and then running their run method.

Instead do this:

new Thread(threadAlpha).start();
new Thread(threadBeta).start();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140463&siteId=1