在java中定义两个不同的Thread

时间:2015-09-15 03:17:09

标签: java multithreading concurrency

我是Threads的新手,我想知道如何定义两个或更多不同的线程在Java程序中做什么。我是否在同一个公共void run方法中定义它们?如果是这样,我该怎么办?我希望Threat t1调用increment方法,t2调用递减方法,并且它们都调用value方法

以下是代码示例:

package interference;

/**
*
* @author rodrigopeniche
*/
public class Interference implements Runnable{

/**
 * @param args the command line arguments
 * 

 */

Counter counter1= new Counter();

class Counter{

    private int c= 0;

    public void increment()
    {
        c++;
    }

    public void decrement()
    {
        c--;
    }

    public int value()
    {
        return c;
    }

}

public static void main(String[] args) {
    // TODO code application logic here


 Thread t1= new Thread(new Interference());
 Thread t2= new Thread(new Interference());
 t1.start();
 t2.start();

}



@Override
public void run() {

counter1.increment();
counter1.decrement();
counter1.value();



}

}

2 个答案:

答案 0 :(得分:1)

您可以将名称设置为thread1, thread2等主题。之后,在run方法中,检查当前运行的线程的名称并执行必要的操作。

如果需要更长时间运行,必须在run方法中添加while循环。

public static void main(String[] args) {

    Interference interference = new Interference();//create a new Interference object

    Thread t1 = new Thread(interference, "thread1");//pass the runnable interference object and set the thread name
    Thread t2 = new Thread(interference, "thread2");//pass the runnable interference object and set the thread name
    t1.start();
    t2.start();
}

@Override
public void run() {

    while (true) {//to run it forever to make the difference more visual

        String threadName = Thread.currentThread().getName();//get the current thread's name
        if (threadName.equals("thread1")) {//if current thread is thread1, increment
            counter1.increment();
        } else if (threadName.equals("thread2")) {//if current thread is thread2, decrement
            counter1.decrement();
        }

        System.out.println(counter1.value());//print the value
    }
}

当您运行代码时,您可以看到计数以随机方式上下移动。

答案 1 :(得分:-1)

在当前代码中,counter1是类Interference的实例变量。您创建了2个Interference实例,然后使用它们创建两个Thread个对象。当线程开始运行时,每个Thread实际上都在处理它自己的counter1副本。我认为这可能不是你所期望的。

package interference;

public class Interference {
    static class Counter {
        private int c = 0;

        public void increment() {
            c++;
        }

        public void decrement() {
            c--;
        }

        public int value() {
            return c;
        }
    }

    public static void main(String[] args) {
        Counter counter = new Counter();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                counter.increment();
                System.out.println(counter.value());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                counter.decrement();
                System.out.println(counter.value());
            }
        });
        t1.start();
        t2.start();
    }
}