本帖最后由 王广彬 于 2012-8-15 00:45 编辑
public class Student {
private Student(){}
private static Student s=new Student ();
public static Student getSingle() {
return s;
}
String name;
int age;
boolean flag = false;
}
public class InputStudent implements Runnable {
Student s=Student.getSingle();
public InputStudent() {}
public InputStudent(Student s) { //此处为什么还要写有参构造???
this.s = s;
}
public void run() {
int x = 0;
while (true) {
synchronized (s) {
if(s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (x % 2 == 0) {
s.name = "林青霞";
s.age = 20;
} else {
s.name = "刘德华";
s.age = 40;
}
//唤醒打印线程
s.flag = true;
s.notify();
}
x++;
}
}
}
public class OutputStudent implements Runnable {
Student s=Student.getSingle();
public OutputStudent() {
}
public OutputStudent(Student s) { //此处为什么还要写有参构造???
this.s = s;
}
public void run() {
while (true) {
synchronized (s) {
if(!s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.name + "***" + s.age);
s.flag = false;
s.notify();
}
}
}
}
public class ResourceTest {
public static void main(String[] args) {
Student s = Student.getSingle();
InputStudent is = new InputStudent(s);
OutputStudent os = new OutputStudent(s);
Thread t1 = new Thread(is);
Thread t2 = new Thread(os);
t1.start();
t2.start();
}
}
在InputStudent和OutputStudent类中为什么还要定义有参构造啊?不是已经调用Student s=Student.getSingle();了吗?
我把那两个构造方法去掉后照样也可以运行.那它们的作用是什么?很是费解!请各位大侠帮帮忙,小弟在此谢过. |