62,614
社区成员
发帖
与我相关
我的任务
分享
public class Test1 {
/**
* 我们用一个买票的例子。 Count为总票数 Get类做买票 Put类做加票
*
* 这里需要用到单例模式
*/
public static Test1 t=null;
private Test1(){
}
public static Test1 getTest1(){
if(t==null){
t=new Test1();
}
return t;
}
private int count = 10;// 初始为10张票
/**
* 线程同步方法,temp 记录是Get类调用还是Put类
*
* @param temp
* 为 1 -->Get类 else Put类
*/
public synchronized int fun(int temp) {
if (temp == 1) {
this.count--;// 每次减少或增加一张
System.out.println(Thread.currentThread().getName()
+ "买票:1张---> 剩余:" + this.count);
} else {
this.count++;
System.out.println(Thread.currentThread().getName()
+ "加票:1张---> 剩余:" + this.count);
}
return this.count;
}
public static void main(String[] args) {
Get get = new Get();
Thread t = new Thread(get, "客户");
Put put = new Put();
Thread t1 = new Thread(put, "车站");
t.start();
t1.start();
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
class Get implements Runnable {
public void run() {
// TODO Auto-generated method stub
Test1 t = Test1.getTest1();
int i = t.getCount();
while (true) {
// 买票
i = t.fun(1);
if (i <= 5) {//当票数小于5张时 才开始加票
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class Put implements Runnable {
public void run() {
// TODO Auto-generated method stub
Test1 t = Test1.getTest1();
int i = t.getCount();
while (true) {
// 加票
i = t.fun(0);
if(i>10){//当票数大于10长 就又开始买票
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
......
AtomicLong count = new AtomicLong(0);
......
thread1 = new Thread() {
public void run(){
count.set(x);
}
};
thread2 = new Thread() {
public void run(){
x = count.get();
}
};
......