Java threads (1)

Multithreading Quick Start

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 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 , will affect the 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.

Why use multithreading?

Reflections on life issues?

Now there are 1000 tons of water, only Xiaoming fetch water, but Xiao Ming fetch water per hour 200 tons, now requires one hour to finish all the water, ask how to solve?

If Xiaoming is over, all the water will need five hours.

  Solution :

While fetching water in Canada four people, were a small army, red, Linda, a small, plus a total of five people Xiao Ming to fetch water at the same time, five people draw water per hour 200 kilograms, it can be done in an hour to play meal finished water.

Summary : the benefits of multi-threading improve efficiency of the program.

Multi-threaded application scenarios?

A : mainly to reflect the multi-threaded program to improve efficiency.

For example : Thunder multi-threaded download, send text messages in batches.

Create a multi-threaded mode

The first inheritance Thread class overrides the run method

 

Code :

 

class CreateThread extends Thread {

// run method to write multithreaded code to be executed

publicvoid run() {

for  ( you i  = 0; i <10; i ++) {

System.out.println("i:" + i);

}

}

}

publicclass ThreadDemo {

 

publicstaticvoid main(String[] args) {

. System OUT .println ( "----- ----- begin to create multi-threaded" );

// Create a thread

CreateThread createThread = new CreateThread();

// 2. Start thread of execution threads instead of calling attention to open the run method, but start method

. System OUT .println ( "Start ----- ----- create multi-threaded" );

createThread.start();

. System OUT .println ( "End ----- ----- create multi-threaded" );

}

 

}

 

 

Allowing the results :

 

Call to start the method, code is not executed from top to bottom, but there is a new executive-thirds

Note: Paint demonstration multithreading different execution paths.

 

The second realization Runnable interfaces , override the run method

Code :

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("-----多线程创建结束-----");

}

}

 

第三种使用匿名内部类方式

 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("-----多线程创建结束-----");

使用继承Thread还是使用实现Runnable接口好?

 使用实现实现Runnable接口好,原因实现了接口还可以继续继承,继承了类不能再继承

启动线程是使用调用start方法还是run方法?

开始执行线程 注意 开启线程不是调用run方法,而是start方法

调用run知识使用实例调用方法。

 

获取线程对象以及名称

常用线程api方法

start()

启动线程

currentThread()

获取当前线程对象

getID()

获取当前线程ID      Thread-编号  该编号从0开始

getName()

获取当前线程名称

sleep(long mill)

休眠线程

Stop()

停止线程,

常用线程构造函数

Thread()

分配一个新的 Thread 对象

ThreadString name

分配一个新的 Thread对象,具有指定的 name正如其名

ThreadRunable r

分配一个新的 Thread对象

ThreadRunable r, String name

分配一个新的 Thread对象

守护线程

 Java有两种线程,一种是用户线程,另一种是守护线程。

 用户线程是用户自定义创建的线程,主线程停止,用户线程不会停止

守护线程进程不存在或主线程停止,守护线程也停止

 使用setDaemon(true)方法设置为守护线程

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("主线程执行完毕!");

}

 

}

 

线程运行状态

 

 线程从创建、运行到结束总是处于下面五个状态之一:新建状态、就绪状态、运行状态、阻塞状态及死亡状态。

状态

   当用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()方法作用

join作用是让其他线程变为等待,  t1.join();// 让其他线程变为等待,直到当前t1线程执行完毕,才释放。

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程AJoin()方法,直到线程A执行完毕后,才会继续执行线程B

需求:

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

 

class JoinThread implements Runnable {

 

public void run() {

for (int i = 0; i < 100; i++) {

System.out.println(Thread.currentThread().getName() + "---i:" + i);

}

}

}

 

 

public class JoinThreadDemo {

 

public static void main(String[] args) {

JoinThread joinThread = new JoinThread();

Thread t1 = new Thread(joinThread);

Thread t2 = new Thread(joinThread);

t1.start();

t2.start();

try {

       //其他线程变为等待状态,等t1线程执行完成之后才能执行join方法。

t1.join();

} catch (Exception e) {

 

}

for (int i = 0; i < 100; i++) {

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()将导致线程从运行状态转到可运行状态,但有可能没有效果。

 

多线程分批处理数据

需求:目前蚂蚁课堂有10万个用户,现在蚂蚁课堂需要做活动,给每一个用户发送一条祝福短信。

为了提高数程序的效率,请使用多线程技术分批发送据。

开一个线程,都会占用CPU资源

服务器(电脑)配置 CPU

建立项目名称:itmayiedu_thread_batch

 

新建用户实体类

package com.itmayiedu.enity;

class UserEntity {

private String userId;

private String userName;

public String getUserId() {

returnuserId;

}

publicvoid setUserId(String userId) {

this.userId = userId;

}

public String getUserName() {

return userName;

}

 

publicvoid setUserName(String userName) {

this.userName = userName;

}

}

 

建立多线程UserThread 执行发送短信

Class UserThreadextends Thread {

private List<UserEntity>list;

/**

 * 通过构造函数 传入每个线程需要执行的发送短信内容

 *

 * @param list

 */

public UserThread(List<UserEntity>list) {

this.list = list;

}

icvoid run() {

for (UserEntity userEntity : list) {

System.out.println("threadName:" + Thread.currentThread().getName() + "-学员编号:" + userEntity.getUserId()

+ "---学员名称:" + userEntity.getUserName());

// 调用发送短信具体代码

}

}

}

 

初始化数据

publicstatic List<UserEntity> init() {

List<UserEntity>list = new ArrayList<UserEntity>();

for (inti = 1; i<= 140; i++) {

UserEntity userEntity = new UserEntity();

userEntity.setUserId("userId" + i);

userEntity.setUserName("userName" + i);

list.add(userEntity);

}

returnlist;

 

}

 

计算分页工具类

static public<T> List<List<T>> splitList(List<T> list, int pageSize) {

int listSize = list.size();

int page = (listSize + (pageSize - 1)) / pageSize;

List<List<T>>listArray = new ArrayList<List<T>>();

for (int i = 0; i<page; i++) {

List<T>subList = new ArrayList<T>();

for (int j = 0; j<listSize; j++) {

int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;

if (pageIndex == (i + 1)) {

subList.add(list.get(j));

}

if ((j + 1) == ((j + 1) * pageSize)) {

break;

}

}

listArray.add(subList);

}

return listArray;

}

}

 

实现发送短信

Public staticvoid main(String[] args) {

// 1.初始化用户数据

List<UserEntity>listUserEntity = init();

// 2.计算创建创建多少个线程并且每一个线程需要执行“分批发送短信用户”

// 每一个线程分批跑多少

intuserThreadPage = 50;

// 计算所有线程数

List<List<UserEntity>>splitUserList = ListUtils.splitList(listUserEntity, userThreadPage);

intthreadSaze = splitUserList.size();

for (inti = 0; i<threadSaze; i++) {

List<UserEntity>list = splitUserList.get(i);

UserThread userThread = new UserThread(list);

// 3.执行任务发送短信

userThread.start();

}

 

}

 

 

 

1. 现在有T1T2T3三个线程,你怎样保证T2T1执行完后执行,T3T2执行完后执行  

代码:

public class JoinThreadDemo02 {

public static void main(String[] args) {

Thread t1 = new Thread(new Runnable() {

public void run() {

for (int i = 0; i < 20; i++) {

System.out.println("t1,i:" + i);

}

}

});

Thread t2 = new Thread(new Runnable() {

public void run() {

try {

t1.join();

} catch (Exception e) {

// TODO: handle exception

}

for (int i = 0; i < 20; i++) {

System.out.println("t2,i:" + i);

}

}

});

Thread t3 = new Thread(new Runnable() {

public void run() {

try {

t2.join();

} catch (Exception e) {

// TODO: handle exception

}

for (int i = 0; i < 20; i++) {

System.out.println("t3,i:" + i);

}

}

});

t1.start();

t2.start();

t3.start();

}

}

 

 

 

 

 

面试题

1.进程与线程的区别?

:进程是所有线程的集合,每一个线程是进程中的一条执行路径,线程只是一条执行路径。

2.为什么要用多线程?

 :提高程序效率

3.多线程创建方式?

  :继承ThreadRunnable 接口。

4.是继承Thread类好还是实现Runnable接口好?

:Runnable接口好,因为实现了接口还可以继续继承。继承Thread类不能再继承。

5.你在哪里用到了多线程?

:主要能体现到多线程提高程序效率。

举例:分批发送短信、迅雷多线程下载等。

-----

Callable

Guess you like

Origin www.cnblogs.com/yhm9/p/10991254.html