public class TestNum {
public static void main(String[] args){
System.out.println(func1(4));
Obj o = new Obj();
Inner i = new Inner(o);
Thread ii = new Thread(i);
outner o1 = new outner(o);
Thread oo = new Thread(o1);
ii.start();
oo.start();
}
}
class Inner implements Runnable{
Obj o;
public Inner(Obj o){
this.o = o;
}
public void run() {
while(true){
o.getInfo();
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class outner implements Runnable{
Obj o;
int i = 0;
public outner(Obj o){
this.o = o;
}
public void run() {
while(true){
if(i%10==0)
o.setInfo("lisi","女");
else
o.setInfo("zhangsan","男");
i++;
try {
o.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Obj{
String name = "unknown";
String sex = "unknown";
//boolean btrue = true;
public synchronized void getInfo() {
System.out.print(name+" sex : ");
System.out.println(sex);
}
public synchronized void setInfo(String name,String sex) {
this.name = name;
this.sex = sex;
}
}
public class TestNum {
public static void main(String[] args) {
Obj o = new Obj();
Inner i = new Inner(o);
Thread ii = new Thread(i);
outner o1 = new outner(o);
Thread oo = new Thread(o1);
ii.start();
oo.start();
}
}class Inner implements Runnable {
Obj o;
public Inner(Obj o) {
this.o = o;
}
public void run() {
while (true) {
o.getInfo();
}
}
}class outner implements Runnable {
Obj o;
int i = 0;
public outner(Obj o) {
this.o = o;
} public void run() {
while (true) {
if (i % 10 == 0) {
o.setInfo("lisi", "女");
} else {
o.setInfo("zhangsan", "男");
}
i++;
}
}
}class Obj {
String name = "unknown";
String sex = "unknown";
boolean isSet = false; public synchronized void getInfo() {
if (isSet) {
System.out.println("get info :" + name + " " + sex);
isSet = false;
notifyAll();
}
try {
wait();
} catch (InterruptedException ex) {
}
} public synchronized void setInfo(String name, String sex) {
if (!isSet) {
this.name = name;
this.sex = sex;
System.out.println("set info :" + name + " " + sex);
isSet = true;
notifyAll();
}
try {
wait();
} catch (InterruptedException ex) {
}
}
}
有wait,notify的地方必有synchronized.这是因为wait和notify不是属于线程类,而是每一个对象都具有的方法,而且,这两个方法都和对象锁有关,有锁的地方,必有synchronized。