62,620
社区成员
发帖
与我相关
我的任务
分享
class A
{
void a(){
while(true)
{
a_fun();
}
}
void a_fun(){
//do sth here
}
};
class B
{
void b(){
while(true)
{
b_fun();
}
}
void b_fun(){
//do sth here
}
};
public class Main{
public static void main(String[] args)
{
A a = new A();
B b = new B();
long time;
while(true){
//运行a
time = System.currentTimeMillis()+10000;
while(System.currentTimeMillis() < time)
a.a_fun();
//运行b
time = System.currentTimeMillis()+10000;
while(System.currentTimeMillis() < time)
b.b_fun();
}
}
}
class A extends Thread
{
void a(){
while(true)
{
synchronized(Main.lock){
while(Main.state != Main.A_RUNNING)
Main.lock.wait();
}
//do sth here
}
}
public void run(){
a();
}
};
class B extends Thread
{
void b(){
while(true)
{
synchronized(Main.lock){
while(Main.state != Main.B_RUNNING)
Main.lock.wait();
}
//do sth here
}
}
public void run(){
b();
}
};
public class Main{
static final byte START = 0;
static final byte A_RUNNING = 1;
static final byte B_RUNNING = 2;
static byte state = START;
static Object lock = new Object();
public static void main(String[] args) throws Exception
{
A a = new A();
B b = new B();
a.start();
b.start();
while(true){
//通知A运行
state = A_RUNNING;
synchronized(lock){
lock.notifyAll();
}
Thread.sleep(10000);//休眠
//通知B运行
state = B_RUNNING;
synchronized(lock){
lock.notifyAll();
}
Thread.sleep(10000);//休眠
}
}
}