Home > OS >  how to write multithreads in java
how to write multithreads in java

Time:11-20

how to Write two thread classes MyThread1 and MyThread2. The first thread will print “hello” 5 times and sleep 1 second each time. The second thread will print “bye” 5 times and sleep 1 second each time. Write the main thread which creates and starts one object of MyThread1 and another of MyThread2 ???

CodePudding user response:

public class Foo {
    
    public static final int TIMES = 5;
    public static final int MSECS = 1_000;
    
    public static void main(String[] args) {
        
        Thread thread1 = new Thread (new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < Foo.TIMES; i  ) {
                    System.out.println("Hello");
                    try {
                        Thread.sleep(Foo.MSECS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
            
        Thread thread2 = new Thread (new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < Foo.TIMES; i  ) {
                    System.out.println("Bye");
                    try {
                        Thread.sleep(Foo.MSECS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }               
            }
        });
        
        thread1.start();
        thread2.start();
        
    }
    
}

It uses anonymous classes in order to keep the whole code inside the main class (I thought it is way more readable), it is not perfect because it's repeating itself within the run() functions (violating DRY principle). Implementing a class which inherites from Runnable would be way better but still less readable.

CodePudding user response:

It's quite simple. See the docs for Thread.

In the case mentioned, see also about sleep, to make the thread go to WAIT, for a specific amount of time (in miliseconds).

And notice that the screen (System.out) is a shared resource, so any use of it should be synchronized.

  • Related