一个循环如何由两个线程完成?说 ist 线程从 count=1 循环到 count=4,第二个线程循环 count=5 到 8?

How can a loop be completed by two thread? say loop from count=1 to count=4 by ist thread and count =5 to 8 by 2nd thread?

关于我想要的输出方式的描述: 我想要两个线程 Gauravjohn 来完成一个 while 循环(从 1 到 8),这样无论哪个线程启动,运行s 进行 5 次迭代(即直到 count=5),然后进入休眠状态,然后下一个线程完成循环(运行 for count=6 to count=8)。程序应该结束了。 对于这种情况,我创建了一个 实例变量 count 并在计数器方法

中递增它的值

问题是:即使在同步计数器方法(计数器方法递增计数变量)之后,我仍然得到一个奇怪的输出(输出附加在最后)

public class ThreadCounter implements Runnable {
   private int count; 
   @Override
   public void run(){

      try {
            counter(); // call synchronized counter function 

       } catch (InterruptedException e) {
        // TODO Auto-generated catch block
         e.printStackTrace();
         }

     }//end of run()

    public synchronized void counter() throws InterruptedException{

           while(true){

           // i want the loop to increment count from 1 to 4 by ist      thread(whichever thread runs ist) and then 5 to 8 by next thread

                 System.out.println("Which thread running ? " +Thread.currentThread().getName());

                 count++;

                 System.out.println("count is"+count);

                 if (count==5){
             System.out.println("count is"+count +" and Thread is " +Thread.currentThread().getName());
            // when count is 5 make the current thread should  go to sleep
               Thread.currentThread().sleep(7000);
              }// if count==5 ends here


        //whichever thread starts now , should start the counter from count=5 

             if (count==8){
                break;
            // when count is 5 make the current thread go to sleep

              }

          }// while loop ends here
   }// end of counter()
}// end of class ThreadingIst

 public class ThreadTest {

    public static void main(String [] args){

        Thread t1= new Thread(new ThreadingIst());

        Thread t2= new Thread(new ThreadingIst());  

        t1.setName("John");
        t2.setName("Gaurav");

    t1.start();
    t2.start();

   }// main ends here

}

输出为:

哪个线程 运行ning ?约翰 计数是 1

哪个线程 运行ning ?约翰 计数是 2

哪个线程 运行ning ?约翰 计数是 3

哪个线程 运行ning ?约翰 计数是 4

哪个线程 运行ning ?约翰 计数是 5

计数为 5,Thread John 即将休眠

哪个线程 运行ning ?高拉夫 计数是 1

哪个线程 运行ning ?高拉夫 计数是 2

哪个线程 运行ning ?高拉夫 计数是 3

哪个线程 运行ning ?高拉夫 计数是 4

哪个线程 运行ning ?高拉夫 计数是 5

count is5 并且 Thread Gauravis 将进入休眠状态

哪个线程 运行ning ?高拉夫 计数是 6

哪个线程 运行ning ?高拉夫 计数是 7

哪个线程 运行ning ?高拉夫 计数为 8

count is8 和 Thread Gauravis 退出循环

哪个线程 运行ning ?约翰 计数是 6

哪个线程 运行ning ?约翰 计数是 7

哪个线程 运行ning ?约翰 计数为 8

计数为 8,Thread John 正在退出循环

我已经完成了一个答案 - "implements Runnable" vs. "extends Thread",其中一条评论是 但是,实现 Runnable 和扩展 Thread 之间的一个显着区别是 通过扩展 Thread,您的每个线程都有一个与之关联的唯一对象,而 实现 Runnable,许多线程可以共享同一个对象实例。

所以,如果线程可以共享同一个对象,那么像 count 这样的实例值应该由两者共享。为什么我的输出是这样的。

一个简单的解决方案是使用 Java 8 条流 API

IntStream.rangeClosed(1, 8).parallel()
         .forEach(System.out::println);

这可以用更少的代码使用您机器中的所有 CPU。

by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.

实际上在这方面没有什么区别,两种情况都可以。

避免子类化 Thread 的原因是为了避免在调用重写方法时造成混淆。

Why is my output like this then.

您正在共享一个没有线程安全的对象。

要实现这一点,您可以创建两个线程,并让一个线程等待另一个线程,您可以在此处阅读有关加入线程的信息:

http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

我在想:

public class Counter extends Thread {
    private final int countFrom;
    private final int countTo;
    private final Counter counterToWaitFor;

    public Counter(final int countFrom, final int countTo, final Counter counterToWaitFor) {
        super();
        this.countFrom = countFrom;
        this.countTo = countTo;
        this.counterToWaitFor = counterToWaitFor;
    }

    @Override
    public void run() {
        if (this.counterToWaitFor != null) {
            try {
                this.counterToWaitFor.join();
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = this.countFrom; i <= this.countTo; i++) {
            System.out.println("i= " + i);
        }
    }
}

主要是:

public static void main(final String[] args) throws IOException, InterruptedException {
    final Counter t1 = new Counter(1, 5, null);
    final Counter t2 = new Counter(6, 8, t1);
    t1.start();
    t2.start();
}