执行代码后算出来总是多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();
}
}