用JAVA写一个多线程程序,生成2个线程,对一个共享变量value,一个加1,另一个线程对变量减1,各自输出。

2025-02-25 21:57:12
推荐回答(3个)
回答1:

代码没有考虑同步问题,不过单一的一次操作,出现同时访问的几率甚小 public class ThreadDemo{ private int value = 0; class Increment extends Thread{ public void run(){ value++; System.out.println("加1后:"+value); } } class Decrement extends Thread{ public void run(){ value--; System.out.println(“减1后:”+value); } } public void doTest(){ new Increment().start(); new Decrement().start(); } public static void main(String args[]){ new ThreadDemo().start(); } }

回答2:

多线程要么集成Thread类 要么实现Runnable 接口 入口都是public void run(){} 如果需要一个完善的可以做一个线程池.

回答3:

public class Test {

private Integer valuep = 0;
public static void main(String[] arr) {
Integer value = 0;
Test test=new Test();
test.test();
System.out.println("value:"+value);
}

public void test(){
new plusThread().run();
new minusThread().run();
}

class plusThread implements Runnable {
@Override
public void run() {
valuep++;
System.out.println("ThreadPlus:"+valuep);
}
}

class minusThread implements Runnable {
@Override
public void run() {
valuep--;
System.out.println("ThreadMinus:"+valuep);
}
}
}