实现个线程加减

package PACKAGE_NAME;

public class Test {

    public static void main(String[] args) {
        thread factory = new thread();
        T1 t1 = new T1(factory);
        T2 t2 = new T2(factory);
        t2.setName("减线程1");

        T2 t3 = new T2(factory);
        t3.setName("减线程2");

        Thread thread1 = new Thread(t1, "加线程1");
        Thread thread2 = new Thread(t1, "加线程2");

        thread1.start();
        thread2.start();
        t2.start();
        t3.start();
    }
}

package PACKAGE_NAME;

public class thread {
    /**
     * 所需加的参数
     */
    private int j;

    thread(){
        j=0;
    }
    synchronized void add() {
        j++;
        System.out.println("+++++++"+Thread.currentThread().getName() + ":" + j);
    }
    synchronized void min() {
        j--;
        System.out.println("-------"+Thread.currentThread().getName() + ":" + j);
    }
}

package PACKAGE_NAME;

public class T1 implements Runnable {

    thread thread = null;

    T1(thread thread) {
        this.thread = thread;
    }
    public int T1() {
        return 1;
    }
    @Override
    public void run() {
        while(true) {
            thread.add();
            try {
                Thread.sleep((int)Math.random() * 10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

package PACKAGE_NAME;

public class T2 extends Thread {

    thread thread = null;

    T2(thread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
        while(true) {
            thread.min();
            try {
                Thread.sleep((int)Math.random() * 10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Java)