有两个线程类 get类和put类,在主线程中有一个变量count,同时启动两个线程,能不能两个类同时工作啊,意思就是一会对count用get类的方法,一会对count用put类的方法?

解决方案 »

  1.   

    不知道你的具体要求,所以只好写点概要的代码......
    AtomicLong count = new AtomicLong(0);
    ......
    thread1 = new Thread() {
        public void run(){
           count.set(x);
        }
    };
    thread2 = new Thread() {
        public void run(){
           x = count.get();
        }
    };
    ......
      

  2.   


    汗 。写了这么久,  你看看满足你要求不。。 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();
    }
    }
    }
    }}