现在有1000顿的水,目前只有小明一个人去打水,但是小明每小时打水200顿,现在要求一小时内把水全部打完,请问怎么解决?
如果小明一个人将水全部打完需要五个小时。
解决办法:
在加四个人同时打水,分别为小军、小红、小玲、小小,加上小明一共五个人同时去打水,五个人每小时打水200千克,那么一小时后就可以完成打完一顿水。
答:主要能体现到多线程提高程序效率。
举例: 迅雷多线程下载、分批发送短信等
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("-----多线程创建结束-----");
}
}
允许结果:
调用start方法后,代码并没有从上往下执行,而是有一条新的执行分支
class CreateRunnable implements Runnable {
@Override
public void run() {
for (inti = 0; i< 10; i++) {
System.out.println("i:" + i);
}
}
}
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("-----多线程创建结束-----");
}
}
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("-----多线程创建结束-----");
使用实现实现Runnable接口好,原因实现了接口还可以继续继承,继承了类不能再继承
开始执行线程 注意 开启线程不是调用run方法,而是start方法
调用run知识使用实例调用方法。
| start() | 启动线程 |
|---|---|
| currentThread() | 获取当前线程对象 |
| getID() | 获取当前线程ID Thread-编号 该编号从0开始 |
| getName() | 获取当前线程名称 |
| sleep(long mill) | 休眠线程 |
| Stop() | 停止线程 |
| Thread() | 分配一个新的 Thread 对象 |
|---|---|
| Thread(String name) | 分配一个新的Thread对象,具有指定的name正如其名. |
| Thread(Runable r) | 分配一个新的 Thread对象 |
| Thread(Runable 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>线程在等待某个触发条件;
有两个原因会导致线程死亡:
join作用是让其他线程变为等待, t1.join();// 让其他线程变为等待,直到当前t1线程执行完毕,才释放。
thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程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();
}
}
Thread.yield()方法的作用:暂停当前正在执行的线程,并执行其他线程。(可能没有效果)
yield()让当前正在运行的线程回到可运行状态,以允许具有相同优先级的其他线程获得运行的机会。因此,使用yield()的目的是让具有相同优先级的线程之间能够适当的轮换执行。但是,实际中无法保证yield()达到让步的目的,因为,让步的线程可能被线程调度程序再次选中。
结论:大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果。
需求:目前有n个车商用户,现在需要做活动,给每一个用户发送短信。
为了提高程序的效率,请使用多线程技术分批发送数据。
每开一个线程,都会占用CPU资源
服务器(电脑)配置 CPU 核数
public class UserEntity {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Class UserThreadextends Thread {
private List<UserEntity>list;
public UserThread(List<UserEntity>list) {
this.list = list;
}
public void run() {
for (UserEntity userEntity : list) {
System.out.println("threadName:" + Thread.currentThread().getName() + "-用户编号:" + userEntity.getUserId()
+ "---用户名称:" + userEntity.getUserName());
// 调用第三方短信接口
}
}
}
public static 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);
}
return list;
}
public class ListUtils {
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 static void 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-99
package com.cheguo.adminmanage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created with IntelliJ IDEA.
*
* @author: yangxianyu
* Date: 2018/6/10
* Time: 下午9:33
* Description:
*/
public class testMain {
static volatile int count = 1;
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.submit(new TestPrint(0,"thread1"));
executorService.submit(new TestPrint(1,"thread2"));
executorService.submit(new TestPrint(2,"thread3"));
}
static class TestPrint implements Runnable{
private int number;
private String threadname;
public TestPrint(int number,String threadname){
this.number=number;
this.threadname=threadname;
}
@Override
public void run() {
synchronized (TestPrint.class){
while (count<100){
if(count/3 % 3 == number){
int j = count;
for(int i = j;i<j+3;i++){
System.out.println(threadname+"|"+count);
count++;
}
TestPrint.class.notifyAll();
}else {
try {
TestPrint.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}