Advanced multi-threaded Java --- Getting Started

There are three things in this world that people can not take away: First, eat into the stomach of food, the second is hidden in the dream, the three books are read into the brain

Multithreading Quick Start

1, the difference between threads and processes

  • Each program running on the system is a process. Each process contains one or more threads. A thread is a set of a set of instructions, or the special section of the program, which can be independently executed in the program. So basically a lightweight process thread, which is responsible for performing multiple tasks in a single program. Usually responsible for scheduling and execution of multiple threads by the operating system.

  • Using threads can occupy a long time in the program into the background task to deal with, running speed of the program is likely to accelerate in the realization of some tasks, such as waiting for user input, file read and write, and send and receive network data, the thread is more useful . In this case you can free up some valuable resources such as memory usage and so on.

  • If a large number of threads can affect performance, because the operating system needs to switch between them, more threads require more memory space, thread suspension need to consider their impact on the program running. Typically model data block is shared among a plurality of threads, the thread needs to prevent a deadlock situation.

  • Summary: The process is the set of all threads, each thread is a path of execution process.

2. Why use multithreading?

  • (1), using multiple threads may reduce the response time of the program . If you have to wait for a single-threaded or obstruction, will cause the program does not respond to mouse, keyboard and other operations, the use of multiple threads can resolve this problem, enhanced interactive program.

  • (2) Compared with the process, thread creation and switching overhead is smaller , because the memory space threads share the code segment, data segment and so on.

  • (3), multi-core CPU, multi-core computer itself has the ability to perform multi-threaded, if a single thread, you can not re-use computing resources, resulting in a huge waste of resources.

  • (4), multi-threading can simplify the structure of the program , make the program easy to maintain, a very complex process can be divided into multiple threads of execution.

3, multi-threaded application scenarios?

  • A: The main embody the multi-threaded program to improve efficiency.
  • Example: Thunder multi-threaded download, database connection pooling, a batch send text messages and so on.

4, multi-threaded way to create

First, the Thread class inheritance override the run method

class CreateThread extends Thread {
    // run方法中编写 多线程需要执行的代码
    publicvoid run() {
        for (inti = 0; i< 10; i++) {
            System.out.println("i:" + i);
        }
    }
}
publicclass ThreadDemo {

    publicstaticvoid main(String[] args) {
        System.out.println("-----多线程创建开始-----");
        // 1.创建一个线程
        CreateThread createThread = new CreateThread();
        // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法
        System.out.println("-----多线程创建启动-----");
        createThread.start();
        System.out.println("-----多线程创建结束-----");
    }

}

  • After the start method is called, the code did not execute from the top down, but there is a new executive branch

  • Note: Paint demonstration multithreading different execution paths.

Second, to achieve Runnable interface, override the run method

class CreateRunnable implements Runnable {

    @Override
    publicvoid run() {
        for (inti = 0; i< 10; i++) {
            System.out.println("i:" + i);
        }
    }

}
publicclass ThreadDemo2 {
    publicstaticvoid main(String[] args) {
        System.out.println("-----多线程创建开始-----");
        // 1.创建一个线程
        CreateRunnable createThread = new CreateRunnable();
        // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法
        System.out.println("-----多线程创建启动-----");
        Thread thread = new Thread(createThread);
        thread.start();
        System.out.println("-----多线程创建结束-----");
    }
}

Third, the use of anonymous inner classes manner

 System.out.println("-----多线程创建开始-----");
         Thread thread = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i< 10; i++) {
                    System.out.println("i:" + i);
                }
            }
        });
         thread.start();
         System.out.println("-----多线程创建结束-----");

5, using inheritance Thread class or Runnable interface that implement good?

  • That implement Runnable interface to achieve good reasons implements the interface can continue inheritance, the class can not be inherited.

6, start the thread start method is called using the method still run?

  • Open thread begins execution threads instead of calling attention to the run method, but start method calls the run method calls the instance knowledge.

7, and the name of the object to obtain a thread

Common threads api method
start() Start a thread
currentThread() Get the current thread object
getID() Get the current thread ID Thread- Number This number starts at 0
getName() Gets the name of the current thread
sleep(long mill) Sleeping thread
Stop() Stop the thread,
Common thread constructor
Thread() Allocates a new Thread object
Thread(String name) Allocates a new Thread object with the specified name as its name.
Thread(Runable r) Allocates a new Thread object
Thread(Runable r, String name) Allocates a new Thread object

8, daemon thread

  • Java, there are two threads, one is the user thread, the other is the guardian of the thread.
  • User thread refers to user-defined thread created, the main thread to stop, will not stop user threads
  • Daemon thread when the process does not exist or stop the main thread, the thread daemon will be stopped.
  • Use setDaemon (true) method to set a daemon thread
public class DaemonThread {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    System.out.println("我是子线程...");
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {

            }
            System.out.println("我是主线程");
        }
        System.out.println("主线程执行完毕!");
    }

}

9, multi-threaded operating status

  •  Thread from creation, always run to the end in one of the following five states: New state , ready state , running state , blocking state and the state of death

New Status

  • 当用new操作符创建一个线程时, 例如new Thread(r),线程还没有开始运行,此时线程处在新建状态。 当一个线程处于新生状态时,程序还没有开始运行线程中的代码

就绪状态

  • 一个新创建的线程并不自动开始运行,要执行线程,必须调用线程的start()方法。当线程对象调用start()方法即启动了线程,start()方法创建线程运行的系统资源,并调度线程运行run()方法。当start()方法返回后,线程就处于就绪状态。
  • 处于就绪状态的线程并不一定立即运行run()方法,线程还必须同其他线程竞争CPU时间,只有获得CPU时间才可以运行线程。因为在单CPU的计算机系统中,不可能同时运行多个线程,一个时刻仅有一个线程处于运行状态。因此此时可能有多个线程处于就绪状态。对多个处于就绪状态的线程是由Java运行时系统的线程调度程序(thread scheduler)来调度的。

运行状态

  • 当线程获得CPU时间后,它才进入运行状态,真正开始执行run()方法.
    阻塞状态线程运行过程中,可能由于各种原因进入阻塞状态:

      1>线程通过调用sleep方法进入睡眠状态;
      2>线程调用一个在I/O上被阻塞的操作,即该操作在输入输出操作完成之前不会返回到它的调用者;

       3>线程试图得到一个锁,而该锁正被其他线程持有;
       4>线程在等待某个触发条件;

死亡状态

  • 有两个原因会导致线程死亡:
     - - 1) run方法正常退出而自然死亡,
     - - 2) 一个未捕获的异常终止了run方法而使线程猝死。
    -  为了确定线程在当前是否存活着(就是要么是可运行的,要么是被阻塞了),需要使用isAlive方法。如果是可运行或被阻塞,这个方法返回true; 如果线程仍旧是new状态且不是可运行的, 或者线程死亡了,则返回false.

join()方法作用

  • 当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1

创建一个线程,子线程执行完毕后,主线程才能执行。

Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {

                    }
                    System.out.println(Thread.currentThread().getName() + "i:" + i);
                }
            }
        });
        t1.start();
        // 当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1
        t1.join();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {

            }
            System.out.println("main" + "i:" + i);
        }
        
  • 优先级
  • 现代操作系统基本采用时分的形式调度运行的线程,线程分配得到的时间片的多少决定了线程使用处理器资源的多少,也对应了线程优先级这个概念。在JAVA线程中,通过一个int priority来控制优先级,范围为1-10,其中10最高,默认值为5。下面是源码(基于1.8)中关于priority的一些量和方法。
class PrioritytThread implements Runnable {

    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().toString() + "---i:" + i);
        }
    }
}
public class ThreadDemo4 {

    public static void main(String[] args) {
        PrioritytThread prioritytThread = new PrioritytThread();
        Thread t1 = new Thread(prioritytThread);
        Thread t2 = new Thread(prioritytThread);
        t1.start();
        // 注意设置了优先级, 不代表每次都一定会被执行。 只是CPU调度会有限分配
        t1.setPriority(10);
        t2.start();
        
    }

}

Yield方法

Thread.yield()方法的作用:暂停当前正在执行的线程,并执行其他线程。(可能没有效果)
yield()让当前正在运行的线程回到可运行状态,以允许具有相同优先级的其他线程获得运行的机会。因此,使用yield()的目的是让具有相同优先级的线程之间能够适当的轮换执行。但是,实际中无法保证yield()达到让步的目的,因为,让步的线程可能被线程调度程序再次选中。
结论:大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果。

总结

  • 1.进程与线程的区别?
    • 答:进程是所有线程的集合,每一个线程是进程中的一条执行路径,线程只是一条执行路径。
  • 2.为什么要用多线程?
    • 答:提高程序效率
  • 3.多线程创建方式?
      • 答:继承Thread或Runnable 接口。
  • 4.是继承Thread类好还是实现Runnable接口好?
    • 答:Runnable接口好,因为实现了接口还可以继续继承。继承Thread类不能再继承。
  • 5.你在哪里用到了多线程?
    • 答:主要能体现到多线程提高程序效率。
    • 举例:分批发送短信、迅雷多线程下载等。

总结不易,给个关注吧 https://github.com/yunlongn

Guess you like

Origin www.cnblogs.com/rolandlee/p/10967171.html