java 多线程问题

import java.util.ArrayList;
import java.util.List;

public class Store {

private List<Integer> st = new ArrayList<Integer>();

public synchronized void add(int i){
if (st.size() == 4) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
st.add(i);
System.out.println("size : " + st.size());
this.notifyAll();
}
}

public synchronized int get(){
if (st.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = st.remove(st.size()-1);
this.notifyAll();
return i;
}
}


public class Producer implements Runnable{
private Store s ;

Producer(Store s){
this.s = s;
}
public void produce(){
System.out.println("produce......");
for (int i = 0; i < 20; i++) {
s.add(i);
System.out.println("produce : " + i);
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void run() {
produce();
}
}



public class Customer implements Runnable{

private Store s ;

Customer(Store s){
this.s = s;
}
public void custom(){
System.out.println("custom.......");
for (int i = 0; i < 20; i++) {
System.out.println("customing : " + s.get());
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void run() {
custom();
}

}


public class Test {

public static void main(String[] args) {
Store s = new Store();
Customer c = new Customer(s);
Producer p = new Producer(s);


new Thread(p).start();
new Thread(c).start();

}

}



------------------------
public class Test implements Runnable{

private static int sum = 10;

private boolean flag = true;

public synchronized void aaaa(){
if (flag) {
sum--;
System.out.println(Thread.currentThread().getName() + "--->" + sum);

}
}
public void run() {
while (true) {
if (sum > 0) {
aaaa();
}else{
System.out.println(Thread.currentThread().getName() + "--->over!");
break;
}
}

}
public static void main(String[] args) {
Test t = new Test();
for (int i = 0; i < 2; i++) {
new Thread(t,"thread no : " + i).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值