Java Programming Thread Runnable

What is Thread?

** Thread ** is a unit of flow that executes processing </ font>. To summarize the computer operation,

You can imagine this series of processing as Thread.


Single thread & multi thread

Single thread (left figure): Thread that ends with only one process Multithread (right figure): Threads in which multiple threads run at the same time

qiita01 (2).png

You can imagine it like this.

Benefits of multithreading

Higher speed processing than single thread is possible.

For example) While working in Microsoft Word, spell checking is being performed and the number of words is displayed at the same time. This is the true value of multithreading.


Basic operation of Thread

--Implement the Runnable interface in your class.

Runnable.java


class class name implements Runnable{
  public void run(){
    /*Write the process*/
  }
}

--Pass and declare a class that implements Runnable as an argument of the Thread constructor.

Thread.java


Thread thread = new Thread(Class type variable);

The reference of Thread type constructor is as follows.

Reference-Thread-Constructor(reference)


Thread
public Thread(Runnable target)

--Starting Thread You can execute the run () method in the class with start () method </ font>.

ThreadStart.java


thread.start();

--Check if Thread is finished Use Thread's join () method </ font>.

  • This time, we will assume that there are multiple Threads in the array.

Join.java


try{
    for(int i=0; i<thread.length; i++){
        thread[i].join();
    }
} catch(InterruptedException ie){
    ie.printStackTrace();
}

Difference between with and without threads

Add 1 to the variable sum. Verification of execution time with and without threads for a program that repeats this 1000000000 times.

Without threads

NoThread.java


import java.util.Date;
import java.math.BigInteger;

public class NoThread{
    private static BigInteger N = new BigInteger("1000000000");
    private static BigInteger sum = BigInteger.ZERO;

    public static void main(String[] args){
        long start_time = new Date().getTime();
        calculate();
        long end_time = new Date().getTime();
        output(start_time, end_time);
    }

    public static void calculate(){
        BigInteger i = BigInteger.ZERO;
        while(!i.equals(N)){
            sum = sum.add(BigInteger.ONE);   // sum += i
            i = i.add(BigInteger.ONE);       // i++
        }
    }

    public static void output(long s, long e){
        System.out.println("Sum: "+sum);
        System.out.println("total time: "+(e-s)+"ms");
    }
}

Execution result: スクリーンショット 2019-06-08 0.06.53.png

Number of threads Execution time
None 46371 ms
  • The processing time is not always constant.

If there is a thread

This time, specify the number of threads in the argument at runtime.

ThreadRun.java


import java.math.BigInteger;
import java.util.Date;

public class ThreadRun{
    private static BigInteger N = new BigInteger("1000000000");
    private static BigInteger sum = BigInteger.ZERO;

    public static void main(String[] args){
        int num_threads = Integer.parseInt(args[0]);
        BigInteger range = N.divide(new BigInteger(args[0]));

        ThreadRunnable[] tr = new ThreadRunnable[num_threads];
        Thread[] t = new Thread[num_threads];

        BigInteger low = BigInteger.ONE;
        BigInteger high = low.add(range);
        long start_time = new Date().getTime();

        for(int i=0; i<num_threads-1; i++){
            tr[i] = new ThreadRunnable(low, high);
            t[i] = new Thread(tr[i]);
            t[i].start();

            low = high.add(BigInteger.ONE);
            high = low.add(range);
        }
        tr[num_threads-1] = new ThreadRunnable(low, high);
        t[num_threads-1] = new Thread(tr[num_threads-1]);
        t[num_threads-1].start();

        try{ // check whether threads finished
            for(int i=0; i<num_threads; i++){
                t[i].join();
            }
        } catch(InterruptedException ie){
            ie.printStackTrace();
        }

        for(int i=0; i<num_threads; i++){
            sum = sum.add(tr[i].getSum());
        }
        
        long end_time = new Date().getTime();
        System.out.println("Sum: "+sum);
        System.out.println("total time: "+(end_time-start_time)+"ms");
    }

    protected static class ThreadRunnable implements Runnable{
        private BigInteger sum_temp;
        private BigInteger low, high;
        public ThreadRunnable(BigInteger l, BigInteger h){
            this.low = l;
            this.high = h;
            this.sum_temp = BigInteger.ZERO;
        }

        @Override
        public void run(){
            while(!low.equals(high)){
                sum_temp = sum_temp.add(BigInteger.ONE);  // sum_temp += low
                low = low.add(BigInteger.ONE); // low++;
            }
        }

        public BigInteger getSum(){
            return sum_temp;
        }
    }
}

Execution result: スクリーンショット 2019-06-08 0.07.05.png If there is a Thread,

Number of threads Execution time
8 26840 ms
16 26462 ms
  • The processing time is not always constant.

Summary

Processing time is shorter with threads than without threads. Effective use of threads can save a lot of time. However, if you increase the number of threads too much, the execution time will increase, so it is important to specify an appropriate number of threads </ font>.

Recommended Posts