标签:
两个线程共用一个对象。
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){} } } }
标签:
原文地址:http://www.cnblogs.com/smilelily/p/5647310.html