[Java] 纯文本查看 复制代码
//测试类
public class BonusDemo {
public static void main(String[] args) {
Bonus bon=new Bonus();
SetThread st=new SetThread(bon);
GetThread gt=new GetThread(bon);
Thread t0= new Thread(st);
t0.setName("红包");
Thread t1 = new Thread(gt);
t1.setName("1号");
Thread t2 = new Thread(gt);
t2.setName("2号");
Thread t3 = new Thread(gt);
t3.setName("3号");
Thread t4 = new Thread(gt);
t4.setName("4号");
Thread t5 = new Thread(gt);
t5.setName("5号");
t0.start();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
import java.util.Random;
//红包资源类
public class Bonus {
private static int count=5;
private static int bonus;
private boolean flag;
public synchronized void set(){
if(this.flag==true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(count>0){
Random r=new Random();
bonus=r.nextInt(10)+1;
count--;
System.out.println("红包已生成");
}
this.flag=true;
this.notify();
}
public synchronized void get(){
if(this.flag==false){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+bonus+"元");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.flag=false;
this.notify();
}
}
public class SetThread implements Runnable {
private static int count=5;
private Bonus bon;
public SetThread(Bonus bon) {
this.bon=bon;
}
public void run() {
while(count>0){
bon.set();
count--;
}
}
}
public class GetThread implements Runnable {
private static int count=5;
private Bonus bon;
public GetThread(Bonus bon) {
this.bon=bon;
}
public void run() {
while(count>0){
count--;
bon.get();
}
}
}
[Java] 纯文本查看 复制代码
import java.util.Random;
//红包资源类
public class Bonus {
private static int count=5;
private static int bonus;
private boolean flag;
public synchronized void set(){
while(this.flag==true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(count>0){
Random r=new Random();
bonus=r.nextInt(10)+1;
count--;
System.out.println("红包已生成");
}
this.flag=true;
this.notifyAll();
}
public synchronized void get(){
while(this.flag==false){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+bonus+"元");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.flag=false;
this.notifyAll();
}
}