qq_41194872
2018-12-30 11:48java多线程,统计每个线程执行次数
执行代码后算出来总是多3
package work2;
public class Part implements Runnable{
private int n = 800;
private int i = 1;
@Override
public void run() {
// TODO Auto-generated method stub
int m = 0;
while(i <= n){
if(i <= n) {
m++;
}
sell();
}
System.out.println(Thread.currentThread().getName()+"生产了:"+m+"个");
}
public synchronized void sell(){
if(i <= n){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i <= n){
System.out.println(Thread.currentThread().getName()+
"生产第"+ i++ +"个零件");
}
}
}
}
package work2;
public class WorkShop {
public static void main(String [] args){
Part part = new Part();
Thread thread1 = new Thread(part, "第一生产车间");
Thread thread2 = new Thread(part, "第二生产车间");
Thread thread3 = new Thread(part, "第三生产车间");
Thread thread4 = new Thread(part, "第四生产车间");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
- 点赞
- 回答
- 收藏
- 复制链接分享
0条回答
为你推荐
- http长连接如何保证一个用户只有一个长连接(一个线程)
- it技术
- 互联网问答
- IT行业问题
- 计算机技术
- 编程语言问答
- 0个回答
- java 求四千多用户的某一排名 如何用多线程 优化for循环
- 优化
- 多线程
- 8个回答