Many concurrent programming threads (Java)

First, 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. It can also be understood as context code run. So basically a lightweight process thread, which is responsible for performing multiple tasks in a single program. Usually responsible for scheduling multiple threads of execution by the operating system and

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.

Second, why should use multiple threads?

Multithreading improve program execution efficiency.
Such as: Thunder multi-threaded download, database connection pooling, a batch send text messages and so on.

Third, create multi-threaded mode

1, the Thread class inheritance override the first method run

/**
 * 
 * @classDesc: 功能描述:(创建多线程例子-Thread类 重写run方法)
 */
class CreateThread extends Thread {
    // run方法中编写 多线程需要执行的代码
    public void run() {
        for (inti = 0; i< 10; i++) {
            System.out.println("i:" + i);
        }
    }
}
public class ThreadDemo {

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

}

2, the second to achieve Runnable interface, override the run method

/**
 * 
 * @classDesc: 功能描述:(创建多线程例子-Thread类 重写run方法)
 */
class CreateRunnable implements Runnable {

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

}

/**
 * 
 * @classDesc: 功能描述:(实现Runnable接口,重写run方法)
 */
public class ThreadDemo2 {
    public static void 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("-----多线程创建结束-----");
    }
}

3, a third embodiment using anonymous inner classes

public class ThreadDemo3 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i< 10; i++) {
                    System.out.println("i:" + i);
                }
            }
        });
         thread.start();
    }
}

Fourth, the common APi

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.

Gets thread object and the name

Common threads api method

start () Starts the thread

currentThread () Gets the current thread object

getID () Gets the current thread ID Thread- Number This number starts at 0

getName () Get the name of the current thread

sleep (long mill) sleeping thread

Stop () to 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) assign a new Thread object

Thread (Runable r, String name) is assigned a new Thread object

Fifth, the 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

thread.setDaemon (to true)
# six, join () method effect

When performing the t1.join () method in which the main thread, the main thread that it should give the execution right T1
`` `Java
the Thread new new the Thread = T1 (the Runnable new new () {

        @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的一些量和方法。java
class PrioritytThread implements Runnable {

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

}

/**

  • @classDesc:
    */
    public class ThreadDemo4 {

    static void main public (String [] args) {
    PrioritytThread prioritytThread new new PrioritytThread = ();
    the Thread = T1 new new the Thread (prioritytThread);
    the Thread T2 = new new the Thread (prioritytThread);
    t1.start ();
    // Note that the priority is set , does not mean that every time will be executed. CPU scheduling will be limited only dispensing
    t1.setPriority (10);
    t2.start ();

    }

}
```

Eight, Yield Methods

Role Thread.yield () method: pause the currently executing thread and other threads to execute. (May not be effective)
yield () so that the thread is currently running back to run the state to allow other threads to have the opportunity to get the same priority to run. Therefore, the purpose of the use of yield () is to be able to have appropriate rotation executed between the same priority thread. However, in practice it can not be guaranteed yield () to achieve the purpose concessions, because concessions thread scheduler thread may be selected again.
Conclusion: In most cases, yield () will cause the thread running from state to state to run, but there may not be effective.

Guess you like

Origin www.cnblogs.com/codeobj/p/11627562.html