java多线程 (2)

  两个线程共用一个对象。

public class threadDemo extends  Thread{

    public static void main(String[] args) {
        ComputerSum sum = new ComputerSum();
        People teacher = new People("teacher",200,sum);
        People student = new People("student",200,sum);
        teacher.start();
        student.start();
    }
}

class ComputerSum{
    int sum;

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }
}

class People extends  Thread{
    int timeLength;
    ComputerSum sum;
    People(String s,int timeLength,ComputerSum sum){
        setName(s);
        this.timeLength = timeLength;
        this.sum = sum;
    }
    
    public void run(){
        for(int i=0; i<5; i++){
            int m = sum.getSum();
            sum.setSum(m+1);
            System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
            try{
                sleep(timeLength);
            }catch(InterruptedException e){}
        }
    }
}

 

posted @ 2016-07-06 16:30  smilelily126  阅读(124)  评论(0编辑  收藏  举报