编程知识 cdmana.com

How to create java thread

 

1、 Inherit Thread Class mode

This approach is applicable to specific tasks , And you need to get the processed data .

Examples : A thread used to accumulate the sum of data in the array .

public class AdditionThread extends Thread {
    private int sum = 0;
    private int[] nums;
​
    public AdditionThread(int[] nums, String threadName) {
        super(threadName);
        this.nums = nums;
    }
​
    @Override
    public void run() {
        for (int num : nums) {
            sum += num;
        }
    }
​
    public int getSum() {
        return sum;
    }
}

Call mode :

public class Main {
    public static void main(String[] args) throws InterruptedException {
        int[] nums = {10, 12, 15, 200, 100};
        AdditionThread thread = new AdditionThread(nums, "AdditionThread");
        thread.start();
        thread.join();
​
        System.out.println("sum=" + thread.getSum());
    }
}

 

2、Runnable Interface mode

Define an implementation Runnable Interface class , Or create an anonymous inner class directly , And cover run() Method . Finally, it is passed as an argument to Thread The constructor of .

public class Main {
    public static void main(String[] args) {
        //  Custom  Runnable
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable, "Runnable-Thread");
        thread.start();
​
        //  Custom anonymous inner class 
        new Thread(() -> {
            System.out.println("Inner class");
        }).start();
    }
​
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("MyRunnable");
        }
    }
}

 

3、 Callable Interface mode

Callable Interface and Runnable Interface differences :

(1)Callable The way is call(),Runnable The way is run().

(2)Callable The method of is returned by the value ,Runnable No .

(3)Callable The method of declaration Exception,Runnable It's not .

public class Main {
    public static void main(String[] args) {
        MyCallable myCallable = new MyCallable();
        FutureTask<String> task = new FutureTask<>(myCallable);
        Thread thread = new Thread(task, "FutureTask");
        thread.start();
        try {
            //  Through get Method to get the return value 
            String result = task.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
​
    static class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            //  Simulate timeout operation 
            Thread.sleep(1000);
            return "OK";
        }
    }
}

 

4、 Thread pool mode

We can go through ThreadPoolExecutor Class to create a thread pool , It can also be done by Executors Factory method to build , Such as

//  Create a thread pool with a fixed number of threads 
Executors.newFixedThreadPool(); 
//  Create a thread pool with only one core thread 
Executors.newSingleThreadExecutor();
//  Create a thread without a core , But you can cache the thread pool of threads 
Executors.newCachedThreadPool();
//  Create a thread pool suitable for executing timed tasks 
Executors.newScheduledThreadPool();

 

When creating a thread pool , It's better to introduce ThreadFactory Arguments , Specifies the name of the thread created by the thread pool . This is conducive to the analysis and positioning of possible problems .

public class Main {
    private static final ExecutorService SERVICE =
        Executors.newFixedThreadPool(5, new BasicThreadFactory("My-Thread"));
​
    public static void main(String[] args) {
        //  Print the name of the thread 
        System.out.println("main thread name:" + Thread.currentThread().getName());
        SERVICE.execute(() -> {
            System.out.println("Hello thread pool.");
            //  Print the name of the thread in the thread pool 
            System.out.println("thread name:" + Thread.currentThread().getName());
        });
    }
​
    static class BasicThreadFactory implements ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(0);
        private final String basicName;
​
        public BasicThreadFactory(String basicName) {
            this.basicName = basicName;
        }
​
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable);
            String name = this.basicName + "-" + threadNumber.incrementAndGet();
            thread.setName(name);
            return thread;
        }
    }
}

&n

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢

Scroll to Top