- package com.lagou.task18;
-
- public class ThreadTest {
-
- public static void main(String[] args) {
-
- // 1.使用无参方式构造Thread类型的对象
- // 由源码可知:Thread类中的成员变量target的数值为null。
- Thread t1 = new Thread();
- // 2.调用run方法进行测试
- // 由源码可知:由于成员变量target的数值为null,因此条件if (target != null)不成立,跳过{}中的代码不执行
- // 而run方法中除了上述代码再无代码,因此证明run方法确实啥也不干
- t1.run();
- // 3.打印一句话
- System.out.println("我想看看你到底是否真的啥也不干!");
- }
- }
18.2.3 相关的方法
|
方法声明
|
功能介绍
|
|
Thread()
|
使用无参的方式构造对象
|
|
Thread(String name)
|
根据参数指定的名称来构造对象
|
|
Thread(Runnable target)
|
根据参数指定的引用来构造对象,其中
Runnable
是个接口类
型
|
|
Thread(Runnable target,
String name)
|
根据参数指定引用和名称来构造对象
|
|
void run()
|
若使用
Runnable
引用构造了线程对象,调用该方法时最终调
用接口中的版本
若没有使用
Runnable
引用构造线程对象,调用该方法时则啥
也不做
|
|
void start()
|
用于启动线程,
Java
虚拟机会自动调用该线程的
run
方法
|
18.2.4 执行流程
- package com.lagou.task18;
-
- public class SubThreadRun extends Thread {
-
- @Override
- public void run() {
- // 打印1 ~ 20之间的所有整数
- for (int i = 1; i <= 20; i++) {
- System.out.println("run方法中:i = " + i); // 1 2 ... 20
- }
- }
- }
- package com.lagou.task18;
-
- public class SubThreadRunTest {
-
- public static void main(String[] args) {
-
- // 1.声明Thread类型的引用指向子类类型的对象
- Thread t1 = new SubThreadRun();
- // 2.调用run方法测试,本质上就是相当于对普通成员方法的调用,因此执行流程就是run方法的代码执行完毕后才能继续向下执行
- //t1.run();
- // 用于启动线程,Java虚拟机会自动调用该线程类中的run方法
- // 相当于又启动了一个线程,加上执行main方法的线程是两个线程
- t1.start();
-
- // 打印1 ~ 20之间的所有整数
- for (int i = 1; i <= 20; i++) {
- System.out.println("-----------------main方法中:i = " + i); // 1 2 ... 20
- }
- }
- }
- package com.lagou.task18;
-
- public class SubRunnableRun implements Runnable {
- @Override
- public void run() {
- // 打印1 ~ 20之间的所有整数
- for (int i = 1; i <= 20; i++) {
- System.out.println("run方法中:i = " + i); // 1 2 ... 20
- }
- }
- }
- package com.lagou.task18;
-
- public class SubRunnableRunTest {
-
- public static void main(String[] args) {
-
- // 1.创建自定义类型的对象,也就是实现Runnable接口类的对象
- SubRunnableRun srr = new SubRunnableRun();
- // 2.使用该对象作为实参构造Thread类型的对象
- // 由源码可知:经过构造方法的调用之后,Thread类中的成员变量target的数值为srr。
- Thread t1 = new Thread(srr);
- // 3.使用Thread类型的对象调用start方法
- // 若使用Runnable引用构造了线程对象,调用该方法(run)时最终调用接口中的版本
- // 由run方法的源码可知:if (target != null) {
- // target.run();
- // }
- // 此时target的数值不为空这个条件成立,执行target.run()的代码,也就是srr.run()的代码
- t1.start();
- //srr.start(); Error
-
- // 打印1 ~ 20之间的所有整数
- for (int i = 1; i <= 20; i++) {
- System.out.println("-----------------main方法中:i = " + i); // 1 2 ... 20
- }
- }
- }
执行main方法的线程叫做主线程,执行run方法的线程叫做新线程/子线程。
- package com.lagou.task18;
-
- public class ThreadNoNameTest {
-
- public static void main(String[] args) {
-
- // 匿名内部类的语法格式:父类/接口类型 引用变量名 = new 父类/接口类型() { 方法的重写 };
- // 1.使用继承加匿名内部类的方式创建并启动线程
- /*Thread t1 = new Thread() {
- @Override
- public void run() {
- System.out.println("张三说:在吗?");
- }
- };
- t1.start();*/
- new Thread() {
- @Override
- public void run() {
- System.out.println("张三说:在吗?");
- }
- }.start();
-
- // 2.使用实现接口加匿名内部类的方式创建并启动线程
- /*Runnable ra = new Runnable() {
- @Override
- public void run() {
- System.out.println("李四说:不在。");
- }
- };
- Thread t2 = new Thread(ra);
- t2.start();*/
- /*new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println("李四说:不在。");
- }
- }).start();*/
- // Java8开始支持lambda表达式: (形参列表)->{方法体;}
- /*Runnable ra = ()-> System.out.println("李四说:不在。");
- new Thread(ra).start();*/
-
- new Thread(()-> System.out.println("李四说:不在。")).start();
- }
- }
18.3 线程的生命周期(熟悉)
|
方法声明
|
功能介绍
|
|
long getId()
|
获取调用对象所表示线程的编号
|
|
String getName()
|
获取调用对象所表示线程的名称
|
|
void setName(String name)
|
设置
/
修改线程的名称为参数指定的数值
|
|
static Thread currentThread()
|
获取当前正在执行线程的引用
|
- package com.lagou.task18;
-
- public class RunnableIdNameTest implements Runnable {
- @Override
- public void run() {
- // 获取当前正在执行线程的引用,也就是子线程的引用
- Thread t1 = Thread.currentThread();
- System.out.println("子线程的编号是:" + t1.getId() + ", 名称是:" + t1.getName()); // 14 guanyu
- t1.setName("zhangfei");
- System.out.println("修改后子线程的编号是:" + t1.getId() + ", 名称是:" + t1.getName()); // 14 zhangfei
- }
-
- public static void main(String[] args) {
-
- RunnableIdNameTest rint = new RunnableIdNameTest();
- //Thread t2 = new Thread(rint);
- Thread t2 = new Thread(rint, "guanyu");
- t2.start();
-
- // 获取当前正在执行线程的引用,当前正在执行的线程是主线程,也就是获取主线程的引用
- Thread t1 = Thread.currentThread();
- System.out.println("主线程的编号是:" + t1.getId() + ", 名称是:" + t1.getName());
- }
- }
- package com.lagou.task18;
-
- public class ThreadIdNameTest extends Thread {
-
- public ThreadIdNameTest(String name) {
- super(name); // 表示调用父类的构造方法
- }
-
- @Override
- public void run() {
- System.out.println("子线程的编号是:" + getId() + ",名称是:" + getName()); // 14 Thread-0 guanyu
- // 修改名称为"zhangfei"
- setName("zhangfei");
- System.out.println("修改后子线程的编号是:" + getId() + ",名称是:" + getName()); // 14 zhangfei
- }
-
- public static void main(String[] args) {
-
- ThreadIdNameTest tint = new ThreadIdNameTest("guanyu");
- tint.start();
-
- // 获取当前正在执行线程的引用,当前正在执行的线程是主线程,也就是获取主线程的引用
- Thread t1 = Thread.currentThread();
- System.out.println("主线程的编号是:" + t1.getId() + ", 名称是:" + t1.getName());
- }
- }
18.5 常用的方法(重点)
|
方法声明
|
功能介绍
|
|
static void yield()
|
当前线程让出处理器(离开
Running
状态),使当前线程进入
Runnable
状态等待
|
|
static void
sleep(times)
|
使当前线程从
Running
放弃处理器进入
Block
状态
,
休眠
times
毫秒
,
再返
回到
Runnable
如果其他线程打断当前线程的
Block(sleep),
就会发生
InterruptedException
。
|
|
int getPriority()
|
获取线程的优先级
|
|
void setPriority(int
newPriority)
|
修改线程的优先级。
优先级越高的线程不一定先执行,但该线程获取到时间片的机会会更多
一些
|
|
void join()
|
等待该线程终止
|
|
void join(long millis)
|
等待参数指定的毫秒数
|
|
boolean isDaemon()
|
用于判断是否为守护线程
|
|
void
setDaemon(boolean
on)
|
用于设置线程为守护线程
|
sleep方法测试:
- package com.lagou.task18;
-
- import java.text.SimpleDateFormat;
- import java.time.LocalDateTime;
- import java.util.Date;
-
- public class ThreadSleepTest extends Thread {
- // 声明一个布尔类型的变量作为循环是否执行的条件
- private boolean flag = true;
-
- // 子类中重写的方法不能抛出更大的异常
- @Override
- public void run() {
- // 每隔一秒获取一次系统时间并打印,模拟时钟的效果
- while (flag) {
- // 获取当前系统时间并调整格式打印
- // LocalDateTime.now();
- Date d1 = new Date();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println(sdf.format(d1));
-
- // 睡眠1秒钟
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public static void main(String[] args) {
-
- ThreadSleepTest tst = new ThreadSleepTest();
- tst.start();
-
- // 主线程等待5秒后结束子线程
- System.out.println("主线程开始等待...");
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 停止子线程 过时 不建议使用
- //tst.stop();
- tst.flag = false;
- System.out.println("主线程等待结束!");
- }
- }
线程优先级方法测试:
- package com.lagou.task18;
-
- public class ThreadPriorityTest extends Thread {
- @Override
- public void run() {
- //System.out.println("子线程的优先级是:" + getPriority()); // 5 10 优先级越高的线程不一定先执行。
- for (int i = 0; i < 20; i++) {
- System.out.println("子线程中:i = " + i);
- }
- }
-
- public static void main(String[] args) {
-
- ThreadPriorityTest tpt = new ThreadPriorityTest();
- // 设置子线程的优先级
- tpt.setPriority(Thread.MAX_PRIORITY);
- tpt.start();
-
- Thread t1 = Thread.currentThread();
- //System.out.println("主线程的优先级是:" + t1.getPriority()); // 5 普通的优先级
- for (int i = 0; i < 20; i++) {
- System.out.println("--主线程中:i = " + i);
- }
- }
-
- }
线程等待方法测试:
- package com.lagou.task18;
-
- public class ThreadJoinTest extends Thread {
- @Override
- public void run() {
- // 模拟倒数10个数的效果
- System.out.println("倒计时开始...");
- for (int i = 10; i > 0; i--) {
- System.out.println(i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println("新年快乐!");
- }
-
- public static void main(String[] args) {
-
- ThreadJoinTest tjt = new ThreadJoinTest();
- tjt.start();
-
- // 主线程开始等待
- System.out.println("主线程开始等待...");
- try {
- // 表示当前正在执行的线程对象等待调用线程对象,也就是主线程等待子线程终止
- //tjt.join();
- tjt.join(5000); // 最多等待5秒
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //System.out.println("终于等到你,还好没放弃!");
- System.out.println("可惜不是你,陪我到最后!");
- }
- }
守护线程测试:
- package com.lagou.task18;
-
- public class ThreadDaemonTest extends Thread {
- @Override
- public void run() {
- //System.out.println(isDaemon()? "该线程是守护线程": "该线程不是守护线程"); // 默认不是守护线程
- // 当子线程不是守护线程时,虽然主线程先结束了,但是子线程依然会继续执行,直到打印完毕所有数据为止
- // 当子线程是守护线程时,当主线程结束后,则子线程随之结束
- for (int i = 0; i < 50; i++) {
- System.out.println("子线程中:i = " + i);
- }
- }
-
- public static void main(String[] args) {
-
- ThreadDaemonTest tdt = new ThreadDaemonTest();
- // 必须在线程启动之前设置子线程为守护线程
- tdt.setDaemon(true);
- tdt.start();
-
- for (int i = 0; i < 20; i++) {
- System.out.println("-------主线程中:i = " + i);
- }
- }
- }
案例题目
- package com.lagou.task18;
-
- public class SubThread1 extends Thread {
- @Override
- public void run() {
- // 打印1 ~ 100之间的所有奇数
- for (int i = 1; i <= 100; i += 2) {
- System.out.println("子线程一中: i = " + i);
- }
- }
- }
- package com.lagou.task18;
-
- public class SubThread2 extends Thread {
- @Override
- public void run() {
- // 打印1 ~ 100之间的所有偶数
- for (int i = 2; i <= 100; i += 2) {
- System.out.println("------子线程二中: i = " + i);
- }
- }
- }
- package com.lagou.task18;
-
- public class SubThreadTest {
-
- public static void main(String[] args) {
-
- SubThread1 st1 = new SubThread1();
- SubThread2 st2 = new SubThread2();
-
- st1.start();
- st2.start();
-
- System.out.println("主线程开始等待...");
- try {
- st1.join();
- st2.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("主线程等待结束!");
- }
- }
- package com.lagou.task18;
-
- public class SubRunnable1 implements Runnable {
- @Override
- public void run() {
- // 打印1 ~ 100之间的所有奇数
- for (int i = 1; i <= 100; i += 2) {
- System.out.println("子线程一中: i = " + i);
- }
- }
- }
- package com.lagou.task18;
-
- public class SubRunnable2 implements Runnable {
- @Override
- public void run() {
- // 打印1 ~ 100之间的所有偶数
- for (int i = 2; i <= 100; i += 2) {
- System.out.println("------子线程二中: i = " + i);
- }
- }
- }
- package com.lagou.task18;
-
- public class SubRunnableTest {
-
- public static void main(String[] args) {
-
- SubRunnable1 sr1 = new SubRunnable1();
- SubRunnable2 sr2 = new SubRunnable2();
-
- Thread t1 = new Thread(sr1);
- Thread t2 = new Thread(sr2);
-
- t1.start();
- t2.start();
-
- System.out.println("主线程开始等待...");
- try {
- t1.join();
- t2.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("主线程等待结束!");
- }
- }
18.6 线程同步机制(重点)
- package com.lagou.task18;
-
- import java.util.concurrent.locks.ReentrantLock;
-
- public class AccountRunnableTest implements Runnable {
- private int balance; // 用于描述账户的余额
- private Demo dm = new Demo();
- private ReentrantLock lock = new ReentrantLock(); // 准备了一把锁
-
- public AccountRunnableTest() {
- }
-
- public AccountRunnableTest(int balance) {
- this.balance = balance;
- }
-
- public int getBalance() {
- return balance;
- }
-
- public void setBalance(int balance) {
- this.balance = balance;
- }
-
- @Override
- public /*synchronized*/ void run() {
- // 开始加锁
- lock.lock();
-
- // 由源码可知:最终是account对象来调用run方法,因此当前正在调用的对象就是account,也就是说this就是account
- //synchronized (this) { // ok
- System.out.println("线程" + Thread.currentThread().getName() + "已启动...");
- //synchronized (dm) { // ok
- //synchronized (new Demo()) { // 锁不住 要求必须是同一个对象
- // 1.模拟从后台查询账户余额的过程
- int temp = getBalance(); // temp = 1000 temp = 1000
- // 2.模拟取款200元的过程
- if (temp >= 200) {
- System.out.println("正在出钞,请稍后...");
- temp -= 200; // temp = 800 temp = 800
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("请取走您的钞票!");
- } else {
- System.out.println("余额不足,请核对您的账户余额!");
- }
- // 3.模拟将最新的账户余额写入到后台
- setBalance(temp); // balance = 800 balance = 800
- //}
- lock.unlock(); // 实现解锁
- }
-
- public static void main(String[] args) {
-
- AccountRunnableTest account = new AccountRunnableTest(1000);
- //AccountRunnableTest account2 = new AccountRunnableTest(1000);
- Thread t1 = new Thread(account);
- Thread t2 = new Thread(account);
- //Thread t2 = new Thread(account2);
- t1.start();
- t2.start();
-
- System.out.println("主线程开始等待...");
- try {
- t1.join();
- //t2.start(); // 也就是等待线程一取款操作结束后再启动线程二
- t2.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("最终的账户余额为:" + account.getBalance()); // 600 800
- }
- }
-
- class Demo{}
18.6.3 实现方式
- package com.lagou.task18;
-
- public class AccountThreadTest extends Thread {
- private int balance; // 用于描述账户的余额
- private static Demo dm = new Demo(); // 隶属于类层级,所有对象共享同一个
-
- public AccountThreadTest() {
- }
-
- public AccountThreadTest(int balance) {
- this.balance = balance;
- }
-
- public int getBalance() {
- return balance;
- }
-
- public void setBalance(int balance) {
- this.balance = balance;
- }
-
- @Override
- public /*static*/ /*synchronized*/ void run() {
- /*System.out.println("线程" + Thread.currentThread().getName() + "已启动...");
- //synchronized (dm) { // ok
- //synchronized (new Demo()) { // 锁不住 要求必须是同一个对象
- // 1.模拟从后台查询账户余额的过程
- int temp = getBalance(); // temp = 1000 temp = 1000
- // 2.模拟取款200元的过程
- if (temp >= 200) {
- System.out.println("正在出钞,请稍后...");
- temp -= 200; // temp = 800 temp = 800
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("请取走您的钞票!");
- } else {
- System.out.println("余额不足,请核对您的账户余额!");
- }
- // 3.模拟将最新的账户余额写入到后台
- setBalance(temp); // balance = 800 balance = 800
- //}*/
- test();
- }
-
- public /*synchronized*/ static void test() {
- synchronized (AccountThreadTest.class) { // 该类型对应的Class对象,由于类型是固定的,因此Class对象也是唯一的,因此可以实现同步
- System.out.println("线程" + Thread.currentThread().getName() + "已启动...");
- //synchronized (dm) { // ok
- //synchronized (new Demo()) { // 锁不住 要求必须是同一个对象
- // 1.模拟从后台查询账户余额的过程
- int temp = 1000; //getBalance(); // temp = 1000 temp = 1000
- // 2.模拟取款200元的过程
- if (temp >= 200) {
- System.out.println("正在出钞,请稍后...");
- temp -= 200; // temp = 800 temp = 800
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("请取走您的钞票!");
- } else {
- System.out.println("余额不足,请核对您的账户余额!");
- }
- // 3.模拟将最新的账户余额写入到后台
- //setBalance(temp); // balance = 800 balance = 800
- }
- }
-
- public static void main(String[] args) {
-
- AccountThreadTest att1 = new AccountThreadTest(1000);
- att1.start();
-
- AccountThreadTest att2 = new AccountThreadTest(1000);
- att2.start();
-
- System.out.println("主线程开始等待...");
- try {
- att1.join();
- //t2.start(); // 也就是等待线程一取款操作结束后再启动线程二
- att2.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("最终的账户余额为:" + att1.getBalance()); // 800
-
- }
-
- }
18.6.4 静态方法的锁定
|
方法声明
|
功能介绍
|
|
ReentrantLock()
|
使用无参方式构造对象
|
|
void lock()
|
获取锁
|
|
void unlock()
|
释放锁
|
|
方法声明
|
功能介绍
|
|
void wait()
|
用于使得线程进入等待状态,直到其它线程调用
notify()
或
notifyAll()
方
法
|
|
void wait(long
timeout)
|
用于进入等待状态,直到其它线程调用方法或参数指定的毫秒数已经过
去为止
|
|
void notify()
|
用于唤醒等待的单个线程
|
|
void notifyAll()
|
用于唤醒等待的所有线程
|
- package com.lagou.task18;
-
- public class ThreadCommunicateTest implements Runnable {
- private int cnt = 1;
-
- @Override
- public void run() {
- while (true) {
- synchronized (this) {
- // 每当有一个线程进来后先大喊一声,调用notify方法
- notify();
- if (cnt <= 100) {
- System.out.println("线程" + Thread.currentThread().getName() + "中:cnt = " + cnt);
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- cnt++;
- // 当前线程打印完毕一个整数后,为了防止继续打印下一个数据,则调用wait方法
- try {
- wait(); // 当前线程进入阻塞状态,自动释放对象锁,必须在锁定的代码中调用
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- break;
- }
- }
- }
- }
-
- public static void main(String[] args) {
-
- ThreadCommunicateTest tct = new ThreadCommunicateTest();
- Thread t1 = new Thread(tct);
- t1.start();
-
- Thread t2 = new Thread(tct);
- t2.start();
- }
- }
18.6.10 线程池(熟悉)
生产者消费者模型:

代码实现:
- package com.lagou.task18;
-
- /**
- * 编程实现仓库类
- */
- public class StoreHouse {
- private int cnt = 0; // 用于记录产品的数量
-
- public synchronized void produceProduct() {
- notify();
- if (cnt < 10) {
- System.out.println("线程" + Thread.currentThread().getName() + "正在生产第" + (cnt+1) + "个产品...");
- cnt++;
- } else {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public synchronized void consumerProduct() {
- notify();
- if (cnt > 0) {
- System.out.println("线程" + Thread.currentThread().getName() + "消费第" + cnt + "个产品");
- cnt--;
- } else {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- package com.lagou.task18;
-
- /**
- * 编程实现生产者线程,不断地生产产品
- */
- public class ProduceThread extends Thread {
- // 声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法 合成复用原则
- private StoreHouse storeHouse;
- // 为了确保两个线程共用同一个仓库
- public ProduceThread(StoreHouse storeHouse) {
- this.storeHouse = storeHouse;
- }
-
- @Override
- public void run() {
- while (true) {
- storeHouse.produceProduct();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- package com.lagou.task18;
-
- public class ConsumerThread extends Thread {
- // 声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法 合成复用原则
- private StoreHouse storeHouse;
- // 为了确保两个线程共用同一个仓库
- public ConsumerThread(StoreHouse storeHouse) {
- this.storeHouse = storeHouse;
- }
-
- @Override
- public void run() {
- while (true) {
- storeHouse.consumerProduct();
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- package com.lagou.task18;
-
- public class StoreHouseTest {
-
- public static void main(String[] args) {
-
- // 创建仓库类的对象
- StoreHouse storeHouse = new StoreHouse();
- // 创建线程类对象并启动
- ProduceThread t1 = new ProduceThread(storeHouse);
- ConsumerThread t2 = new ConsumerThread(storeHouse);
- t1.start();
- t2.start();
- }
- }
(1)实现Callable接口
|
方法声明
|
功能介绍
|
|
V call()
|
计算结果并返回
|
(2)FutureTask类
|
方法声明
|
功能介绍
|
|
FutureTask(Callable callable)
|
根据参数指定的引用来创建一个未来任务
|
|
V get()
|
获取
call
方法计算的结果
|
- package com.lagou.task18;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
-
- public class ThreadCallableTest implements Callable {
-
- @Override
- public Object call() throws Exception {
- // 计算1 ~ 10000之间的累加和并打印返回
- int sum = 0;
- for (int i = 1; i <= 10000; i++) {
- sum +=i;
- }
- System.out.println("计算的累加和是:" + sum); // 50005000
- return sum;
- }
-
- public static void main(String[] args) {
-
- ThreadCallableTest tct = new ThreadCallableTest();
- FutureTask ft = new FutureTask(tct);
- Thread t1 = new Thread(ft);
- t1.start();
- Object obj = null;
- try {
- obj = ft.get();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- System.out.println("线程处理方法的返回值是:" + obj); // 50005000
- }
- }
|
方法声明
|
功能介绍
|
|
static ExecutorService newCachedThreadPool()
|
创建一个可根据需要创建新线程的
线程池
|
|
static ExecutorService newFixedThreadPool(int
nThreads)
|
创建一个可重用固定线程数的线程
池
|
|
static ExecutorService newSingleThreadExecutor()
|
创建一个只有一个线程的线程池
|
|
方法声明
|
功能介绍
|
|
void execute(Runnable command)
|
执行任务和命令,通常用于执行
Runnable
|
|
Future submit(Callable task)
|
执行任务和命令,通常用于执行
Callable
|
|
void shutdown()
|
启动有序关闭
|
- package com.lagou.task18;
-
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
-
- public class ThreadPoolTest {
-
- public static void main(String[] args) {
-
- // 1.创建一个线程池
- ExecutorService executorService = Executors.newFixedThreadPool(10);
- // 2.向线程池中布置任务
- executorService.submit(new ThreadCallableTest());
- // 3.关闭线程池
- executorService.shutdown();
- }
- }