使用Thread.run()在Enhanced循环中同时执行两个线程

时间:2021-09-06 06:56:03
public abstract class Multithread implements Runnable{
    static Thread t1 = new Thread(){
        public  synchronized void run(){
            try {
                for(;;){
                    System.out.println("java");
                    t1.sleep(300);
                }
            } catch (Exception e) {
                System.out.println("Exception"+e);
            }
        }
    };
    static Thread t2 = new Thread(){
        public  synchronized void  run(){
            try{
                for(;;){
                    System.out.println("world");
                    t2.sleep(300);
                }
            }catch(Exception e){
                System.out.println("Exception"+e);
            }
        }
    };
    public static void main(String[] args) {
        try{
            t1.start();
            t2.start();
        }catch(Exception e){
            System.out.println("Exception "+e);
        }
    }
    @Override
    public void run() {
        System.out.println("running");
    }
}

Excepted O/P:

java
world
java
world
java
world
.
.
.
.

observed I tried using sleep() for the threads,they are getting overlapped at some point of time like this-

观察我尝试使用sleep()作为线程,它们在某些时间点重叠,如下所示 -

java
java
world
java
world
world 
java 
..

Expected i need these two threads to run in parallel and it should not get overlapped,either of the thread can be started. Any idea?

预计我需要这两个线程并行运行,它不应该重叠,任何一个线程都可以启动。任何的想法?

3 个解决方案

#1


1  

Threads are not accurate in time. If they depend on each other, you have to manually synchronize, like : How to execute two threads Sequentially in a class

线程不准确。如果它们相互依赖,则必须手动同步,例如:如何在类中顺序执行两个线程

#2


1  

You can achieve this by having a counter, if the counter is 0 thread 1 executes, increments the counter and calls notyfyAll() on the counter, if the counter is 1 thread 1 calls wait() on the counter. And vice versa for thread 2.

你可以通过一个计数器实现这一点,如果计数器是0线程1执行,增加计数器并调用计数器上的notyfyAll(),如果计数器是1线程1调用计数器上的wait()。线程2反之亦然。

#3


0  

When you execute two threads in parallel, each one of them is executed independently by the underlying operating system. The task scheduler can decide when to execute which thread. This can result in uneven time distribution like you are experiencing.

当您并行执行两个线程时,它们中的每一个都由底层操作系统独立执行。任务调度程序可以决定何时执行哪个线程。这可能会导致您遇到的时间分布不均匀。

One solution for this is to use shared Semaphores to lock each thread until the other one has finished its task. Each thread would then take two semaphores, one for itself and one for the other thread. Both semaphores would start with one permit, so the first release() call doesn't block. The threads would then work like that (psudocode):

对此的一个解决方案是使用共享信号量来锁定每个线程,直到另一个线程完成其任务。然后每个线程将获取两个信号量,一个用于自身,另一个用于另一个线程。两个信号量都以一个许可开始,因此第一个release()调用不会阻塞。然后线程会像那样工作(psudocode):

for (;;) {
    otherThreadSemaphore.acquire(); // blocks until the other thread called release()
    performWork();
    ownThreadSemaphore.release(); // allows the other thread to perform another iteration
}

Another would be to move the infinite loop out of the threads. In each iteration of the loop you spawn both threads, then use thread.yield() to wait until both threads are finished and then the loop starts again creating two new threads. But note that creating threads can be an expensive operation, so you should only do this when the threads do considerable amount of work in each iteration so that this doesn't matter much.

另一种方法是将无限循环移出线程。在循环的每次迭代中,您生成两个线程,然后使用thread.yield()等待两个线程完成,然后循环再次开始创建两个新线程。但请注意,创建线程可能是一项昂贵的操作,因此只有当线程在每次迭代中执行大量工作时才应执行此操作,这样做无关紧要。

#1


1  

Threads are not accurate in time. If they depend on each other, you have to manually synchronize, like : How to execute two threads Sequentially in a class

线程不准确。如果它们相互依赖,则必须手动同步,例如:如何在类中顺序执行两个线程

#2


1  

You can achieve this by having a counter, if the counter is 0 thread 1 executes, increments the counter and calls notyfyAll() on the counter, if the counter is 1 thread 1 calls wait() on the counter. And vice versa for thread 2.

你可以通过一个计数器实现这一点,如果计数器是0线程1执行,增加计数器并调用计数器上的notyfyAll(),如果计数器是1线程1调用计数器上的wait()。线程2反之亦然。

#3


0  

When you execute two threads in parallel, each one of them is executed independently by the underlying operating system. The task scheduler can decide when to execute which thread. This can result in uneven time distribution like you are experiencing.

当您并行执行两个线程时,它们中的每一个都由底层操作系统独立执行。任务调度程序可以决定何时执行哪个线程。这可能会导致您遇到的时间分布不均匀。

One solution for this is to use shared Semaphores to lock each thread until the other one has finished its task. Each thread would then take two semaphores, one for itself and one for the other thread. Both semaphores would start with one permit, so the first release() call doesn't block. The threads would then work like that (psudocode):

对此的一个解决方案是使用共享信号量来锁定每个线程,直到另一个线程完成其任务。然后每个线程将获取两个信号量,一个用于自身,另一个用于另一个线程。两个信号量都以一个许可开始,因此第一个release()调用不会阻塞。然后线程会像那样工作(psudocode):

for (;;) {
    otherThreadSemaphore.acquire(); // blocks until the other thread called release()
    performWork();
    ownThreadSemaphore.release(); // allows the other thread to perform another iteration
}

Another would be to move the infinite loop out of the threads. In each iteration of the loop you spawn both threads, then use thread.yield() to wait until both threads are finished and then the loop starts again creating two new threads. But note that creating threads can be an expensive operation, so you should only do this when the threads do considerable amount of work in each iteration so that this doesn't matter much.

另一种方法是将无限循环移出线程。在循环的每次迭代中,您生成两个线程,然后使用thread.yield()等待两个线程完成,然后循环再次开始创建两个新线程。但请注意,创建线程可能是一项昂贵的操作,因此只有当线程在每次迭代中执行大量工作时才应执行此操作,这样做无关紧要。