我在线程休眠时无法运行任务

问题描述 投票:2回答:1

在我们的系统中,我受命创建一个页面,该页面将实时显示我们系统的主要线程。

为了重新创建一个主要的进程,我打算创建一个线程并使它休眠至少5秒钟。当所述线程处于休眠状态时,我将获取所有活动线程,查看我创建的线程是否在那里,然后将线程信息存储到我的modelMap中,该信息将在我的JSP上传递以显示它。

但是,当我尝试执行此操作时,我设法创建的测试等待线程首先完成睡眠,而不是我希望它执行的操作。

我的主线程:

        SampleThread1 sampleThread1 = new SampleThread1();
        sampleThread1.setName("SAMPLE THREAD 1");
        sampleThread1.run();

        initializeMajorProcess ();

        sampleThread1.interrupt();

SampleThread1:

    class SampleThread1 extends Thread {
        public void run () {
            try {
                System.out.println("-------- thread is starting");              
                Thread.sleep(5000);
                System.out.println("-------- thread is done");              
            } catch (InterruptedException e) {
                System.out.println(this.getName() + "Interrupted");
            }
        }
    }

initializeMajorProcess:

    private String initializeMajorProcess () {
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        Set<Thread> nonDaemonThreads = new HashSet<Thread>();

        for (Thread thread : threadSet) {
            if (thread.isDaemon() == false && !thread.getName().startsWith("MyScheduler")) {
                System.out.println(thread.getId());
                System.out.println(thread.getName());
                System.out.println(thread.isAlive());
                nonDaemonThreads.add(thread);
            }
        }

        return "frps/DeveloperDashboard";
    }

我只是一个有一年工作经验的初级开发人员。这是我第一次处理线程,也是我第一次询问StackOverflow,所以请不要对我这么粗略:((

我也想问我如何实时显示线程信息?我必须使用WebSocket还是必须使用AJAX?

java multithreading java-threads
1个回答
0
投票

[Thread.sleep(5000);]使正在执行的主线程(即您的主类)处于睡眠状态,因为您尚未触发线程,而只是调用了run方法。

因此,而不是调用sampleThread1.start();代替sampleThread1.run();

© www.soinside.com 2019 - 2024. All rights reserved.