老杜java基础入门作业:两个线程对同一对象内的int类型数据交替输出奇数偶数。
import java.util.ArrayList;
import java.util.List;
public class HomeWorkJiaoTiShuChu {
public static void main(String[] args){
ShuChuZhi x = new ShuChuZhi();
Thread c1= new Thread(new XianCheng1(x));
Thread c2= new Thread(new XianCheng2(x));
c1.setName("线程一奇数");
c2.setName("线程二偶数");
c1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
c2.start();
}
}
class ShuChuZhi {
private int i;
public int getI() {
return i;
}
public int addI(){
return i++;
}
}
class XianCheng1 implements Runnable{
private ShuChuZhi i;
public XianCheng1(ShuChuZhi i) {
this.i = i;
}
@Override
public void run() {
while(i.getI()<100){
synchronized (i){
if(i.getI()%2==1){
System.out.println(Thread.currentThread().getName()+"输出"+i.addI());
i.notify();
}
else {
try {
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class XianCheng2 implements Runnable{
private ShuChuZhi i;
public XianCheng2(ShuChuZhi i) {
this.i = i;
}
@Override
public void run() {
while(i.getI()<100){
synchronized (i){
if(i.getI()%2==0){
System.out.println(Thread.currentThread().getName()+"输出"+i.addI());
i.notify();
}
else {
try {
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}