代码没有考虑同步问题,不过单一的一次操作,出现同时访问的几率甚小 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(); } }
多线程要么集成Thread类 要么实现Runnable 接口 入口都是public void run(){} 如果需要一个完善的可以做一个线程池.
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);
}
}
}