前言:Java的JVM允许程序运行多个线程,通过创建java.lang.Thread
类来体现。
多线程多创建:
一、方法一:继承于Thread类
1、创建一个继承于Thread类的子类。
2、重写Thread类的run()
。---->将此线程执行的操作声明在run()中
3、创建Thread类的子对象。
4、通过此对象调用start()
。
public class ThreadTest {
public static void main(String[] args){
//创建Thread类的子对象
MyThread t1=new MyThread();
//通过此对象调用start()
//一方面是启动当前线程,另一方面是调用当前线程的run()。
t1.start();
//我们不能通过直接调用run()方法的方式启动线程。
// t1.run();
//再执行一次start(),会报错
// t1.start();
//如下操作仍然是在main线程中执行的
for (int i=0;i<100;i++){
if(i%2==0){
System.out.println("hello");
}
}
}
}
//创建一个继承于Thread类的子类
class MyThread extends Thread{
//重写Thread类的run()。
@Override
public void run() {
for (int i=0;i<100;i++){
if(i%2==0){
System.out.println(i);
}
}
}
}
通过此对象调用start()
方法的两个作用:一方面是启动当前线程,另一方面是调用当前线程的run()
。
我们不能通过直接调用run()
方法的方式启动线程。
不可以让已经start()
的线程去再次执行,会报IllegalThreadStateException。
如果想要再次调用start()
,只能重写创建一个对象。
5.Thread类中的有关方法
(1)start()
:启动当前线程,调用当前线程的run()
。
(2)run()
:通常需要重写Thread类中的此方法,将创建的线程执行的操作声明在此方法中。
(3)currentThread()
:静态方法,返回执行当前代码的线程。
(4)getName()
:获取当前线程的名字。
(5)setName()
:设置当前线程的名字。
1⃣️也可以通过构造器来命名。
(6)yielsd()
:释放当前cpu的执行权。
(7)join()
:在线程a中调用线程b的join()方法,此时线程a就进入堵塞状态,直到线程b完全执行完以后,线程a才结束堵塞状态。
(8)stop()
:已经过时了。当执行此方法时,强制结束当前线程。
(9)sleep()(long millitime)
:让当前线程“睡眠”指定的milltime毫秒。在指定的millitime毫秒时间内,当前线程是堵塞状态。
(10)isAlive()
:判断当前线程是否还存活。
public class ThreadMethodTest {
public static void main(String[] args){
MyThread1 h1=new MyThread1();
h1.setName("线程一");
h1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
for (int i=0;i<100;i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
if (i==20) {
try {
h1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//判断线程一是否还存活
System.out.println(h1.isAlive());
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i=0;i<100;i++){
if(i%2==0){
//只能用try-catch-finally
//不能用throws,因为父类在此处没有异常
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+i);
}
if(i%20==0){
yield();
}
}
}
}
6.举例:继承Thread方式,多窗口买票。
使用继承Thread来实现
//此处代码存在线程安全问题,会在后续的内容中解决的
public class WindowTest {
public static void main(String[] args){
Window t1=new Window();
Window t2=new Window();
Window t3=new Window();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window extends Thread{
private static int ticket=100;
@Override
public void run() {
while (true){
if (ticket>0){
System.out.println(getName()+":卖票,票号为:"+ticket);
ticket--;
}else {
break;
}
}
}
}
二、方法二:实现Runnable接口
1、创建一个实现了Runnable接口的类。
2、实现类去实现Runnable中的抽象方法:run()
。
3、创建实现类的对象。
4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象。
5、通过Thread类的对象调用start()
:启动线程,调用当前线程的run()
。—>调用了Runnable类型的target的run()
。
public class ThreadTest1 {
public static void main(String[] args){
MyThread2 myThread=new MyThread2();
Thread m1=new Thread(myThread);
m1.start();
//再启动一个线程
Thread m2=new Thread(myThread);
m2.start();
}
}
class MyThread2 implements Runnable{
@Override
public void run() {
for(int i=0;i<100;i++){
if (i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
6.举例:多窗口买票。通过Runnable接口来实现
//此处代码存在线程安全问题,会在后续的内容中解决的
public class WindowTest1 {
public static void main(String[] args){
Window1 w=new Window1();
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
t1.setName("窗口一");
t2.setName("窗口二");
t3.setName("窗口三");
t1.start();
t2.start();
t3.start();
}
}
class Window1 implements Runnable{
private static int ticket=100;
@Override
public void run() {
while (true){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+":卖票,票号为:"+ticket);
ticket--;
}else {
break;
}
}
}
}
三、线程的调度:
详解线程的调度
四、两种创建方式的比较
(1)开发中,优先选择:实现Runnable接口的方式。原因:
1⃣️实现的方式没有类的单继承性的局限性。
2⃣️实现的方式更适合来处理多个线程有共享数据的情况。
(2)联系:
public class Thread implements Runnable
相同点:两种方式都需要重写run()
,将线程要执行的逻辑声明在run()
中。
五、方法三:实现Callable接口
1.与使用Runnable相比,Callable功能更强大。
2.call()方法
1⃣️相比run()方法,可以有返回值。
2⃣️可以抛出异常。
3⃣️支持泛型的返回值。
4⃣️需要借助FutureTask类,比如获取返回结果。
3.Future接口
1⃣️可以对具体Runnable、Callable任务对执行结果进行取消、查询是否完成、获取结果等。
2⃣️FutureTask是Future接口等唯一实现类。
3⃣️FutureTask同时实现了Runnable,Future接口。它既可以作为Runnable被线程执行,又可以作为Future得到Callable等返回值。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class ThreadNew {
public static void main(String[] args){
//3.创建Callable接口实现类的对象
NumThread numThread=new NumThread();
//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask=new FutureTask(numThread);
//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()方法
new Thread(futureTask).start();
try {
//get()方法的返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
Object sum=futureTask.get();
System.out.println("总和为:"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
//2.实现call方法,将此线程需要执行的操作声明在call方法中
@Override
public Object call() throws Exception {
int sum=0;
for (int i=1;i<=100;i++){
if(i%2==0){
System.out.println(i);
sum+=i;
}
}
return sum;
}
}
4.如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程更强大?
1⃣️call()方法可以有返回值。
2⃣️call()方法可以抛出异常,被外面的操作捕获,获取信息。
3⃣️Callable是支持泛型的。
六、方法四:使用线程池
1.背景:经常创建和销毁、使用量特别大的资源,比如并发下的线程,对性能影响很大。
2.思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
3.好处:
(1)提高响应速度(减少了创建新线程的时间)
(2)降低资源消耗(重复利用线程池中线程,不需要每次都创建)
(3)便于线程管理:
1⃣️corePoolSize:核心池的大小。
2⃣️maximumPoolSize:最大线程数。
3⃣️keepAliveTime:线程没有任务时最多保持多长时间后会终止。
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPool {
public static void main(String[] args){
//1.提供指定线程数量的线程池
ExecutorService service= Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1=(ThreadPoolExecutor) service;
//设置线程池的属性
// System.out.println(service.getClass());
// service1.setCorePoolSize(15);
// service1.setKeepAliveTime();
//2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
service.execute(new NumberThread());//适合使用于Runnable
// service.submit(); //适合使用于Callable
service.execute(new NumberThread1());
//3.关闭连接池
service.shutdown();
}
}
class NumberThread implements Runnable{
@Override
public void run() {
for (int i=0;i<=100;i++){
if (i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for (int i=0;i<=100;i++){
if (i%2!=0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}