程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何制作并发运行的线程?

发布于2021-04-14 10:28     阅读(1043)     评论(0)     点赞(13)     收藏(5)


我想让两个单独的线程运行不同类的两个不同实例,并且希望它们同时执行run命令。

我开设了一个练习班来演示我所遇到的问题。一个赛车向前计数,另一个赛车向后计数。

public class testCount {

    public static void main(String args[]) {
        testCount countCompetition = new testCount();
        countCompetition.run();
    }

    public void run() {
        (new Thread(new racer1())).start();
        (new Thread(new racer2())).start();
    }

    public class racer1 implements Runnable {
        public void run() {
            for(int x = 0; x < 100; x++) {
                System.out.println(x);
            }
        }
    }
    public class racer2 implements Runnable {
        public void run() {
            for(int y = 100; y > 0; y--) {
                System.out.println(y);
            }
        }
    }
}

我的结果

1
2
... All the way to 100
100
100
99
... All the way back down
1

我想要的是

1
100
2
99
3
98

他们不需要像这样轮流,但是他们确实需要同时工作,而不是一个接一个地工作。任何提示,建议或代码段将不胜感激。


解决方案


只需Thread.sleep(1);racer之后添加每个System.out.println()

即它将看起来像这样:

public class racer1 implements Runnable {
    public void run() {
        for(int x = 0; x < 100; x++) {
            System.out.println(x);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/154191/7e8d1e8aa0c5d39394d7/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)