62,614
社区成员
发帖
与我相关
我的任务
分享
import org.junit.Test;
public class Main2 {
int MAX_num = 1000;
static int apple = 200;
@Test
public void main() {
Runnable creator = new Runnable() {
public void run() {
create();
}
private void create() {
while (true) {
if (apple < MAX_num) {
synchronized (Main2.this) {
apple++;
System.out.println("apple已有:" + apple);
if (apple == MAX_num) {
try {
Main2.this.notifyAll();
Main2.this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
};
Runnable customeRunnable = new Runnable() {
@Override
public void run() {
custom();
}
private void custom() {
while (true) {
if (apple != 0) {
synchronized (Main2.this) {
apple--;
System.out.println("apple剩下:" + apple);
if (apple == 0) {
Main2.this.notifyAll();
try {
Main2.this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
};
Thread customerThread = new Thread(customeRunnable);
Thread creatorThread = new Thread(creator);
creatorThread.start();
customerThread.start();
}
}
public class Test {
static int MAX_num = 1000;
static int apple = 200;
public static void main(String[] args) {
Runnable creator = new Runnable() {
public void run() {
create();
}
private void create() {
while (true) {
if (apple < MAX_num) {
synchronized (Test.class) {
apple++;
System.out.println("apple已有:" + apple);
if (apple == MAX_num) {
try {
Test.class.notifyAll();
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
};
Runnable customeRunnable = new Runnable() {
@Override
public void run() {
custom();
}
private void custom() {
while (true) {
if (apple != 0) {
synchronized (Test.class) {
apple--;
System.out.println("apple剩下:" + apple);
if (apple == 0) {
Test.class.notifyAll();
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
};
Thread customerThread = new Thread(customeRunnable);
Thread creatorThread = new Thread(creator);
creatorThread.start();
customerThread.start();
}
}