Java concurrency BASICS (I) -- Thread, java concurrency basics thread

Source: Internet
Author: User

Java concurrency BASICS (I) -- Thread, java concurrency basics thread

Concurrent Programming allows us to divide programs into multiple separate and independent tasks. With the multi-thread mechanism, these independent tasks will be driven by the execution thread. When a thread is used, the CPU will take turns to allocate time to each task. Each task feels that it is occupying the CPU. However, the CPU time is actually divided into fragments and allocated to all tasks.

Define a task

Inherit Thread class

We can inherit the Thread class and override the run method.

public class SimpleThread extends Thread {    @Override    public void run(){        for(int i = 0; i < 5; i++){            System.out.println(getName() + i);        }    }        public static void main(String[] args) {        SimpleThread thread = new SimpleThread();        thread.start();        System.out.println(Thread.currentThread().getName());    }}

Implement the Runnable interface

Of course, we can also implement the Runnable interface, implement the run interface, and then submit it to the Thread instance.

public class Task implements Runnable{    public void run(){        for(int i = 0; i < 5; i++){            System.out.println(Thread.currentThread().getName() + i);        }    }    public static void main(String[] args) {        Thread thread = new Thread(new Task());        thread.start();        System.out.println(Thread.currentThread().getName());    }}

Callable and Future

We know that the run method has no return value, which means that the result cannot be obtained after the task is completed. Therefore, we need the Callable interface to help us return the task result. It is similar to the Runnable interface, therefore, we also need to implement the call method of the Callable interface. The Future interface is used to obtain the asynchronous computing result. We can obtain, cancel, or determine whether the execution result is complete. However, the Callable interface does not inherit Runnable, so it cannot be directly submitted to the Thread instance. Therefore, we also need the FutureTask class, which simultaneously implements the Runnable interface and Callable interface, we can use FutureTask to wrap the Callable object and submit it to the Thread instance.

import java.util.concurrent.*;public class TaskWithResult implements Callable<Integer> {    public Integer call(){        int total = 0;        for(int i = 0; i < 100; i++){            total += i;        }        return total;    }    public static void main(String[] args) throws InterruptedException, ExecutionException{        RunnableFuture<Integer> task = new FutureTask<Integer>(new TaskWithResult());        Thread thread = new Thread(task);        thread.start();        while (!task.isDone()){            System.out.println(task.get().toString());        }    }}

Background thread

A background thread, also called a daemon thread, is a thread that provides a common service in the background when the program is running. This thread is not an indispensable part of the program. Therefore, when all non-Background threads end, the background threads are also terminated, regardless of whether the background threads are completed or not. In addition, the subthread of the background thread is also a background thread.

public class Daemon implements Runnable {    @Override    public void run() {        for(int i = 0; i < 10; i++){            try{                Thread.sleep(1000);                System.out.println(i);            }catch (InterruptedException e){                System.out.println(e.getMessage());            }        }    }    public static void main(String[] args) throws InterruptedException{        Thread thread = new Thread(new Daemon());        thread.setDaemon(true);        thread.start();        Thread.sleep(1000 * 5);        System.out.println(Thread.currentThread().getName());    }}

Note that the setDaemon method must be called before start before it can be set as a background thread.

Thread Lifecycle

New)

When a thread is created, it will only be in this state for a short time. At this time, it has allocated necessary system resources and executed initialization. Now that the thread is eligible for CPU time, the scheduler will change the thread to a running or blocking state.

Ready (Runnable)

In this state, the thread can run as long as the scheduler assigns the time slice to the thread. That is to say, the thread can run or not run at any time. As long as the scheduler can allocate time slices to the thread, it can run, which is different from the dead and blocked states.

Blocked)

A thread can run, but a certain condition prevents it from running. When the thread is in the blocking status, the scheduler ignores the thread and does not allocate any CPU time to the thread. It is not possible to execute operations until the thread enters the ready state again.

A task is blocked for the following reasons:

(1) call sleep () to sleep the task. In this case, the task will not run within the specified time.

(2) The thread is suspended by calling wait. The thread enters the ready state only when the thread gets the notify () or notifyAll () message.

(3) The task is waiting for an input/output to complete.

(4) A task tries to call its synchronization control method on an object, but the object lock is unavailable because another task has obtained the lock.

Dead)

A thread in the dead or terminated state is no longer schedulable, and no longer gets the CPU time. Its task has ended or is no longer runable. The normal way of task death is returned from the run () method, but the task thread can be interrupted.

Thread control

Thread priority

The thread priority transmits the thread importance to the scheduler. Although the order of the CPU to process the existing thread set is uncertain, the scheduler will tend to first execute the thread with the highest priority. Of course, this does not mean that threads with lower priority will not be executed (the priority will not lead to deadlocks ). We can use getPriority () to read the priority of an existing thread and modify it through setPriority. Although JDK has 10 priorities, it cannot map well with most operating systems. Therefore, MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY are generally used for priority setting.

Sleep)

Call the sleep method during thread execution to sleep (that is, enter the blocking status ). Sleep will throw InterruptedException.

Public class Sleep {public static void main (String [] args) {System. out. println ("sleep starts"); try {Thread. sleep (1000*2);} catch (InterruptedException e) {System. out. println (e. getMessage ();} System. out. println ("sleep ends ");}}

Concession (Yield)

If you know that you have completed the work required in an iteration of the run method loop, you can give a hint to the thread scheduling mechanism: Your work is almost done, other threads can use the CPU.

The suggestion will be made by calling yeild. Of course, this is just a suggestion and there is no mechanism to ensure it will adopt it. After the thread is switched out, only the ready thread with the same priority as the current thread or higher priority than the current thread will get the execution opportunity. Therefore, it is entirely possible that after the thread is transferred to the ready state, the scheduler schedules it again and re-executes it.

Join
Join allows a thread to wait for the execution of another thread to complete, and the calling thread will be blocked until it isjoin.

public class Task implements Runnable{    public void run(){        for(int i = 0; i < 5; i++){            System.out.println(Thread.currentThread().getName() + i);        }        try{            Thread.sleep(1000);        }catch (InterruptedException e){            System.out.println(e.getMessage());        }    }    public static void main(String[] args) throws Exception{        Thread thread = new Thread(new Task());        thread.start();        thread.join();        System.out.println(Thread.currentThread().getName());    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.