加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 可运行的界面示例

发布时间:2020-12-14 16:34:17 所属栏目:Java 来源:网络整理
导读:public class CreateThreadRunnableExample implements Runnable { public void run() { for (int i = 0; i 5; i++) { System.out.println("Child Thread : " + i); try { Thread.sleep(50); } catch (InterruptedException ie) { System.out.println("Child
public class CreateThreadRunnableExample implements Runnable {

    public void run() {

        for (int i = 0; i < 5; i++) {
            System.out.println("Child Thread : " + i);

            try {
                Thread.sleep(50);
            } catch (InterruptedException ie) {
                System.out.println("Child thread interrupted! " + ie);
            }
        }

        System.out.println("Child thread finished!");
    }

    public static void main(String[] args) {

        Thread t = new Thread(new CreateThreadRunnableExample(),"My Thread");

        t.start();

        for (int i = 0; i < 5; i++) {

            System.out.println("Main thread : " + i);

            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
                System.out.println("Child thread interrupted! " + ie);
            }
        }
        System.out.println("Main thread finished!");
    }
}

在这个程序中,两种睡眠方式都使用了不同的时间..,所以如果主线程运行时间,那么子线程必须运行2次,但它只运行一次….我们采取可运行或运行的概念然后当主线程结束时,那么2个子线程将处于就绪状态,为什么只有一个子线程运行.

解决方法

睡眠方法不是100%时间准确,如 JavaDoc所述:

public static void sleep(long millis)
throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds,subject to the precision and
accuracy of system timers and schedulers. The thread does not lose
ownership of any monitors.

所以基本上这些代码有时候可以像预期一样工作,而其他的时候不行.

另外,你似乎只有一个孩子,所以你为什么期待2?

编辑:从理论上说,当主线程睡着时,子线程应该执行两次.话虽如此,如JavaDoc所述,sleep方法执行的准确性取决于运行它的系统,有时候可能会让其按预期工作,而在其他时间不执行.因此,例如,您可能会遇到主线程睡眠的情况,97毫秒,而不是100,而孩子睡眠时间为53毫秒.这将导致小孩只执行一次.

另一个选择是做这样的事情:while(currentTime = = timeNeededToElapse){currentTime = …}.这导致一个紧张的循环,这可以提供更好的控制,但仍然是,据我所知,不是100%准确,更不要说,你将消耗CPU周期有效地做什么,所以谨慎使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读