一个线程题目

dlookhere 2008-04-03 10:37:49
用JAVA写4个线程,其中两个线程每次对J增加1,另外两个对J减少1,怎么写?
...全文
214 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
fige257 2008-04-05
  • 打赏
  • 举报
回复
两位高手
charmlin 2008-04-05
  • 打赏
  • 举报
回复
学习
token1984 2008-04-05
  • 打赏
  • 举报
回复
mark 学习中
wenzheng38 2008-04-04
  • 打赏
  • 举报
回复
楼上两位都是高手啊
学习下...
贝壳鱼 2008-04-03
  • 打赏
  • 举报
回复
class A {
static final B b;
public A() {
b = = new B();
}

public void executeIncrease() {
new Thread(new Runnable(){
public void run() {
while (true) {
try {
b.increaseJ();
Thread.sleep(500L);
} catch (Exception e) {e.printStackTrace();}
}
}
}).start();
}

public void executeReduce() {
new Thread(new Runnable(){
public void run() {
while (true) {
try {
b.reduceJ();
Thread.sleep(500L);
} catch (Exception e) {e.printStackTrace();}
}
}
}).start();
}


public static void main(String[] args) {
A a0 = new A()
a0.executeIncrease();
A a1 = new A();
a1.executeReduce();
}
}


class B {
int j;
public B() {
}
public void increaseJ() {
j++;
}
public void reduceJ() {
j--;
}
}


用两个线程不行吗
cursor_wang 2008-04-03
  • 打赏
  • 举报
回复
public class ThreadTest1{
private int j;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}
private synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
}
class Inc implements Runnable{
public void run(){
for(int i=0;i<100;i++){
inc();
}
}
}
class Dec implements Runnable{
public void run(){
for(int i=0;i<100;i++){
dec();
}
}
}
}

62,623

社区成员

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

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