方法一:利用内部类实现,两个实现加减的类实现Runnable接口,然后再实现4个具体线程。
package com.jn.test;
public class ManyThreads {
private int j;
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{
@Override
public void run(){
for(int i=0;i<5;i++){
inc();
}
}
}
class Dec implements Runnable{
@Override
public void run(){
for(int i=0;i<5;i++){
dec();
}
}
}
public static void main(String[] args){
ManyThreads threads = new ManyThreads();
Inc inc = threads.new Inc();
Dec dec = threads.new Dec();
for(int i=0;i<2;i++){
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
}
第二种方式:具体加减操作写在一个类的方法里,没有内部类,用另外一个类去调用。
package com.jn.test;
public class ManyThreads2 {
private int j;
public synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
public synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
}
}
调用类:package com.jn.test;
public class ThreadTest {
private ManyThreads2 many = new ManyThreads2();
public void test() {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
many.inc();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
many.dec();
}
}
}).start();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest tTest = new ThreadTest();
tTest.test();
}
}