【问题标题】:Threads to perform only print certain numbers of range执行的线程只打印一定数量的范围
【发布时间】:2015-01-12 11:52:59
【问题描述】:

我有 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() 方法中提到的条件的数字?

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    这不是它的工作原理;使用类似的东西。

    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();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2020-06-20
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多