java多线程,统计每个线程执行次数

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!