执行的线程只打印一定数量的范围

时间:2015-01-12 11:52:59

标签: java multithreading

我有2个帖子,他们想以这种方式执行某些过程

Public Class MyThread implements Runnable{
in public void run(){

for(int i=0;i<=20;i++)
//t1 thread will come & print 1 to 10 numbers only
//t2 thread will come & print next numbers i.e 11 to 20 only. 

}

}

public Class MainClass{

public static void main(String arg[]){

MyThread obj=new MyThread();
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.start();
t2.start();

}
}

如何限制我的线程只打印带有run()方法中提到的条件的数字?

1 个答案:

答案 0 :(得分:3)

这不是它的运作方式;使用这样的东西。

class NumberPrinter implements Runnable
{

    private final int start, end;

    public NumberPrinter(int start, int end)
    {
        this.start = start;
        this.end = end;
    }

    @Override
    public void run()
    {
        for (int i = start; i <= end; ++i)
            System.out.println(i);
    } 
}

通话:

Thread t1 = new Thread(new NumberPrinter(1, 10));
Thread t2 = new Thread(new NumberPrinter(11, 20));
t1.start();
t2.start();

当然,您必须展开此示例(例如,检查起始值是否小于结束值),但这会给您一个粗略的想法。