不同类的两个线程可以共享变量吗

yuji_tt 2010-11-04 07:47:26
有两个线程类 get类和put类,在主线程中有一个变量count,同时启动两个线程,能不能两个类同时工作啊,意思就是一会对count用get类的方法,一会对count用put类的方法?
...全文
209 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
凉岑玉 2010-11-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 whut0802 的回复:]
可以。。。最好同步了
[/Quote]

哥··你好邪恶啊!!
我不是IT男 2010-11-07
  • 打赏
  • 举报
回复

汗 。写了这么久, 你看看满足你要求不。。

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();
}
}
}
}

}

clariones 2010-11-04
  • 打赏
  • 举报
回复
不知道你的具体要求,所以只好写点概要的代码

......
AtomicLong count = new AtomicLong(0);
......
thread1 = new Thread() {
public void run(){
count.set(x);
}
};
thread2 = new Thread() {
public void run(){
x = count.get();
}
};
......
Apeipo 2010-11-04
  • 打赏
  • 举报
回复
注意同步.,
kebin0001 2010-11-04
  • 打赏
  • 举报
回复
靜態變數就行了。
yuji_tt 2010-11-04
  • 打赏
  • 举报
回复
具体怎么实现啊。。。代码证明写啊。。。
whut0802 2010-11-04
  • 打赏
  • 举报
回复
可以。。。最好同步了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧