我是靠谱客的博主 留胡子草莓,这篇文章主要介绍java runnable类_Java中实现Runnable接口的类使用for循环时不能处理同一个对象资源?...,现在分享给大家,希望可以做个参考。

在学习Java的多线程,看到Runnable接口的时候

写了一段小代码,有点搞不懂了

Runnable接口相比Thread类,可以实现对象资源共享

我的代码是用for循环让多个线程数数,共10个数字,三个线程一起数

结果三个线程给我数出30个数字来了

我找过网上的博文,他们写的是卖票程序

多个售票点(线程)一起售卖总共100张票

我和他的代码进行对比,唯一的区别在于,循环计数时

我用的是for循环,他用的是while

于是我就修改了一下代码,

发现用while循环就能实现我希望的:三个进程一起数10个数

虽然实现了需求,但是我有疑问,为什么用for就会数出30个数?

请各位高手赐教,谢谢!

代码如下:

for循环的:

class Test22_06 implements Runnable{

public void run(){

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

System.out.println("线程" + Thread.currentThread().getName() + "数了第" + i + "个数字。");

}

}

}

public class JavaTest22_06{

public static void main(String args[]){

Test22_06 t = new Test22_06();

new Thread(t).start();

new Thread(t).start();

new Thread(t).start();

}

}

while循环的:

class Test22_06 implements Runnable{

int i = 0;

public void run(){

while(i<11){

System.out.println("线程" + Thread.currentThread().getName() + "数了第" + (i++) + "个数字。");

}

}

}

public class JavaTest22_06{

public static void main(String args[]){

Test22_06 t = new Test22_06();

new Thread(t).start();

new Thread(t).start();

new Thread(t).start();

}

}

最后

以上就是留胡子草莓最近收集整理的关于java runnable类_Java中实现Runnable接口的类使用for循环时不能处理同一个对象资源?...的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部