How to run a thread after another?

后端 未结 3 460
一整个雨季
一整个雨季 2021-01-28 00:22

Create three threads and the main thread. Execute each thread as simultaneous tasks. Display information when exiting each thread.

相关标签:
3条回答
  • 2021-01-28 01:06

    It's unclear what you want three threads to do. With two threads you have one waiting on the bool to be false and one waiting on it to be true, right? With three threads you need three states to wait on. You also need to be really careful to set it up in a way so the state transitions happens exactly in the right order and a set amount of times.

    Either try to write that program, and tell us what goes wrong, or if you want design help it might be good to tell us more about what you want to achieve in the end.

    A suggestion if you have a real multithreaded problem that needs to be solved is to look into something like queues. They are really nice high level abstractions that makes working with threads much nicer.

    More likely though, you have some artificial task that needs to be solved, and then you need to speak a bit about the constraints you have.

    0 讨论(0)
  • 2021-01-28 01:12

    public class sync extends Thread {

    public void run() {
    
        synchronized (this) {
            for (int i = 5; i > 0; i--) {
                System.out.print("Thread Name :" + Thread.currentThread().getName() + i+"\n");
            }
        }
    }
    

    }

    class demo {

    public static void main(String args[]) {
        sync obj1 =new sync();
        sync obj2 =new sync();
        sync obj3 =new sync();
        obj1.setName("First");
        obj2.setName("Second");
        obj3.setName("Third");
        obj1.start();
        obj2.start();
        obj3.start();
    }
    

    }

    O/p:
    

    Thread Name :First5 Thread Name :First4 Thread Name :First3 Thread Name :First2 Thread Name :First1 Thread Name :Second5 Thread Name :Second4 Thread Name :Second3 Thread Name :Second2 Thread Name :Second1 Thread Name :Third5 Thread Name :Third4 Thread Name :Third3 Thread Name :Third2 Thread Name :Third1

    HOPE THIS HELPS :)

    0 讨论(0)
  • 2021-01-28 01:19

    Read tutorials here about Thread synchronization in Java.

    0 讨论(0)
提交回复
热议问题