我也是对线程同步问题很困惑,看来半天的视频有又看看书,依葫芦画瓢能出了一下代码:
[code=java]package com.threadtest;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
Temp temp=new Temp();
Thread1 th1 = new Thread1(temp);
Thread2 th2 = new Thread2(temp);
Thread t = new Thread(th1);
Thread t2 = new Thread(th2);
t.start();
t2.start();
}
}
class Thread1 implements Runnable {
int num = 100;
Temp temp;
public Thread1(Temp temp) {
super();
this.temp = temp;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (num > 0) {
if(temp.isFlag()==true){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread1 running "
+ num--);
temp.flagfalse();
}
}
}
}
class Thread2 implements Runnable {
int num = 100;
Temp temp;
public Thread2(Temp temp) {
super();
this.temp = temp;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (num > 0) {
if(temp.isFlag()==false){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread2 running " + num--);
temp.flagtrue();
}
}
}
}
class Temp {
private boolean flag = false;
public boolean isFlag() {
return flag;
}
public synchronized void flagtrue() {
this.flag = true;
}
public synchronized void flagfalse() {
this.flag = false;
}
}[/code]
运行结果跟要求的一样 自己拿去测一下。用到的Temp类中的flag相当于一个公共信号灯一样一个负责开一个负责关 |