码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程 (2)

时间:2016-07-06 18:03:21      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

  两个线程共用一个对象。

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){}
        }
    }
}

 

java多线程 (2)

标签:

原文地址:http://www.cnblogs.com/smilelily/p/5647310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!