黑马程序员技术交流社区
标题:
多线程问题
[打印本页]
作者:
王广彬
时间:
2012-8-15 00:31
标题:
多线程问题
本帖最后由 王广彬 于 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();了吗?
我把那两个构造方法去掉后照样也可以运行.那它们的作用是什么?很是费解!请各位大侠帮帮忙,小弟在此谢过.
作者:
贾成龙
时间:
2012-8-15 00:46
其实没有什么作用,你传了也是指的Student同一个对象,不传也是指向了Student同一个对象,这是上面单例(饿汉式)造成的结果,你写了感觉代码很繁琐。不如不写。
哈哈!个人的小见解,不用谢。广彬兄很威武啊!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2