Java Thread Example

Java Thread Example

JULY 11, 2016 BY PANKAJ 11 COMMENTS

Welcome to the Java Thread Example. Process and Thread are two basic units of execution. Concurrency programming is more concerned with java threads.

Process

A process is a self contained execution environment and it can be seen as a program or application. However a program itself contains multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.

Thread

Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

Java Thread Example

java thread example
Every java application has at least one thread – main thread. Although there are so many other java threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first java thread and we can create multiple threads from it.

Multithreading refers to two or more threads executing concurrently in a single program. A computer single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different processes and threads.

Java Thread Benefits

  1. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
  2. Threads share their parent process data and code
  3. Context switching between threads is usually less expensive than between processes.
  4. Thread intercommunication is relatively easy than process communication.

Java provides two ways to create a thread programmatically.

  1. Implementing the java.lang.Runnable interface.
  2. Extending the java.lang.Thread class.

Java Thread Example – implementing Runnable interface

To make a class runnable, we can implement java.lang.Runnable interface and provide implementation inpublic void run() method. To use this class as Thread, we need to create a Thread object by passing object of this runnable class and then call start() method to execute the run() method in a separate thread.

Here is a java thread example by implementing Runnable interface.

package com.journaldev.threads;

public class HeavyWorkRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            //Get database connection, delete unused data from DB
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }

}

Java Thread Example – extending Thread class

We can extend java.lang.Thread class to create our own java thread class and override run() method. Then we can create it’s object and call start() method to execute our custom java thread class run method.

 

 

Here is a simple java thread example showing how to extend Thread class.

package com.journaldev.threads;

public class MyThread extends Thread {

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("MyThread - START "+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            //Get database connection, delete unused data from DB
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("MyThread - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }
    
}

Here is a test program showing how to create a java thread and execute it.

package com.journaldev.threads;

public class ThreadRunExample {

    public static void main(String[] args){
        Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
        Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
        System.out.println("Starting Runnable threads");
        t1.start();
        t2.start();
        System.out.println("Runnable Threads has been started");
        Thread t3 = new MyThread("t3");
        Thread t4 = new MyThread("t4");
        System.out.println("Starting MyThreads");
        t3.start();
        t4.start();
        System.out.println("MyThreads has been started");
        
    }
}

Output of the above java thread example program is:

Starting Runnable threads
Runnable Threads has been started
Doing heavy processing - START t1
Doing heavy processing - START t2
Starting MyThreads
MyThread - START Thread-0
MyThreads has been started
MyThread - START Thread-1
Doing heavy processing - END t2
MyThread - END Thread-1
MyThread - END Thread-0
Doing heavy processing - END t1

Once we start any thread, it’s execution depends on the OS implementation of time slicing and we can’t control their execution. However we can set threads priority but even then it doesn’t guarantee that higher priority thread will be executed first.

Run the above program multiple times and you will see that there is no pattern of threads start and end.

Runnable vs Thread

If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it as Thread. If your class only goal is to run as Thread, you can extend Thread class.

Implementing Runnable is preferred because java supports implementing multiple interfaces. If you extend Thread class, you can’t extend any other classes.

Tip: As you have noticed that thread doesn’t return any value but what if we want our thread to do some processing and then return the result to our client program, check our Java Callable Future.

Update: From Java 8 onwards, Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class. For more details, check out Java 8 Functional Interfaces.

转载于:https://my.oschina.net/liangzhenghui/blog/908491

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个使用 Java 实现多线程调用方法的示例: ``` public class MultiThreadExample { public static void main(String[] args) { // 创建两个线程 Thread thread1 = new Thread(new Task("Thread 1")); Thread thread2 = new Thread(new Task("Thread 2")); // 启动两个线程 thread1.start(); thread2.start(); } } class Task implements Runnable { private String name; public Task(String name) { this.name = name; } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + " is running iteration " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 在这个示例中,我们创建了两个线程,并通过实现 `Runnable` 接口并重写 `run` 方法实现了两个线程的行为。最后,我们通过调用 `thread1.start()` 和 `thread2.start()` 来启动这两个线程。 ### 回答2: 以下是一个Java多线程调用函数的示例: ```java public class MultithreadExample { public static void main(String[] args) { // 创建一个Runnable对象 Runnable task = () -> { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } }; // 创建并启动三个线程分别调用该函数 Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); Thread thread3 = new Thread(task); thread1.start(); thread2.start(); thread3.start(); } } ``` 上述代码中,我们首先创建了一个实现了Runnable接口的任务(即函数),任务会输出当前运行线程的名称以及计数器的值。 然后,我们创建了三个线程thread1、thread2和thread3,并将任务分配给它们。最后,我们分别启动这三个线程。 当程序执行时,每个线程都会独立运行任务,并输出各自的线程名称和计数器的值。由于是多线程调用同一个函数,所以输出的结果可能会交错,但总体上会保持各个线程连续地输出自己的值。 注意:多线程编程需要注意线程安全和同步的问题,以确保多个线程正确地访问和操作共享资源。 ### 回答3: 这是一个Java多线程调用函数的示例: ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MultiThreadExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); // 创建Callable对象 Callable<Integer> task = () -> { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } return sum; }; // 提交任务并获取Future对象 Future<Integer> future1 = executor.submit(task); Future<Integer> future2 = executor.submit(task); try { // 获取结果并输出 int result1 = future1.get(); int result2 = future2.get(); System.out.println("线程1的计算结果:" + result1); System.out.println("线程2的计算结果:" + result2); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭线程池 executor.shutdown(); } } } ``` 以上示例中创建了一个固定大小为5的线程池,然后定义了一个可调用的任务`task`,这个任务会计算从1到10的累加和。然后通过`executor.submit(task)`方法将任务提交给线程池,返回一个`Future`对象,表示异步的计算结果。 通过`future.get()`方法可以获取每个线程返回的结果,在示例中分别输出了线程1和线程2的计算结果。 最后调用`executor.shutdown()`方法关闭线程池。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值