2个回答
展开全部
public class TestThread extends Thread {
public static void main(String[] args) {
TestThread p = new TestThread();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.start();
t2.start();
System.out.println(t1.activeCount());
System.out.println(t2.activeCount());
}
}
activeCount()方法返回的是当前线程的线程组中活动线程的数目。结果是3,为什么是3呢?因为程序执行main方法时也相当于启动了一个线程。还有就是一定要在线程启动后调用这个方法并打印,不然编译不了,假如程序比较长,放在最后的话结果可能是1,因为那时你的线程已经死亡了、结束了,剩下的就是main这一个线程。
public static void main(String[] args) {
TestThread p = new TestThread();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.start();
t2.start();
System.out.println(t1.activeCount());
System.out.println(t2.activeCount());
}
}
activeCount()方法返回的是当前线程的线程组中活动线程的数目。结果是3,为什么是3呢?因为程序执行main方法时也相当于启动了一个线程。还有就是一定要在线程启动后调用这个方法并打印,不然编译不了,假如程序比较长,放在最后的话结果可能是1,因为那时你的线程已经死亡了、结束了,剩下的就是main这一个线程。
展开全部
public class E2 {
public static void main(String[] args) {
People teacher, student;
ComputerSum sum = new ComputerSum();
teacher = new People("老师", 200, sum);
student = new People("学生", 200, sum);
teacher.start();
student.start();
}
}
class ComputerSum {
int sum;
public void setSum(int n) {
sum = n;
}
public int getSum() {
return sum;
}
}
class People extends Thread {
int timeLength;// 线程的休眠时间长度
ComputerSum sum;
People(String s, int timeLength, ComputerSum sum) {
setName(s);// 调用Thread类的方法setName为线程起名字
this.timeLength = timeLength;
this.sum = sum;
}
public void run() {
for (int i = 1; i <= 5; i++) {
int m = sum.getSum();
sum.setSum(m + 1);
System.out.println("我是" + getName() + ", 现在的和:" + sum.getSum());
try {
sleep(timeLength);
} catch (InterruptedException e) {
}
}
}
}
public static void main(String[] args) {
People teacher, student;
ComputerSum sum = new ComputerSum();
teacher = new People("老师", 200, sum);
student = new People("学生", 200, sum);
teacher.start();
student.start();
}
}
class ComputerSum {
int sum;
public void setSum(int n) {
sum = n;
}
public int getSum() {
return sum;
}
}
class People extends Thread {
int timeLength;// 线程的休眠时间长度
ComputerSum sum;
People(String s, int timeLength, ComputerSum sum) {
setName(s);// 调用Thread类的方法setName为线程起名字
this.timeLength = timeLength;
this.sum = sum;
}
public void run() {
for (int i = 1; i <= 5; i++) {
int m = sum.getSum();
sum.setSum(m + 1);
System.out.println("我是" + getName() + ", 现在的和:" + sum.getSum());
try {
sleep(timeLength);
} catch (InterruptedException e) {
}
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询