例子部分参考验证:
https://blog.csdn.net/qq_34996727/article/details/80416277?utm_medium=distribute.pc_relevant.none-task-blog-OPENSEARCH-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-OPENSEARCH-3.channel_param
1 实现线程执行单元
把标题从 1 创建线程 更新为 1 实现线程执行单元的方式。
java中只有Thread代表线程。Runnable只是将业务相关的代码抽象为一个接口。这涉及到一种设计模式:策略模式。
因此创建线程new线程的方式只有一种。
实现线程执行单元线程体的方式有两种。
例1.继承Thread类方式
代码:
package com.whl.thread;
/**
* 注:
* java.lang包中放着java最核心最基础的类、接口:Object、System、Thread、Runnable
* Thread.currentThread()获取当前cpu执行线程
*/
public class TestThread {
public static void main(String[] args) {
/**
* step 3:在方法中新建一个刚才写的类
*/
MyThread myThread = new MyThread();// 线程处于新建状态
myThread.start();// 就绪状态
for(int i = 0;i < 10;i++) {
System.out.println("hello "+Thread.currentThread().getName());
}
}
}
/**
* step 1:写一个类继承java.lang.Thread
*/
class MyThread extends Thread {
/**
* step 2:复写java.lang.Thread中的run()方法
*/
@Override
public void run() {
// 运行
// TODO 你的线程代码
for(int i = 0;i < 10;i++) {
System.out.println("hello "+Thread.currentThread().getName());
}
}
}
运行结果:
例2.实现Runnable接口方式
代码
package com.whl.thread;
public class TestThread2 {
public static void main(String[] args) {
/**
* step 3:创建实现类
*/
MyRunnable myRunnable = new MyRunnable();
/**
* step 4:创建Thread,传入实现类
*/
Thread thread = new Thread(myRunnable);
/**
* step 5:调用start()方法
*/
thread.start();
for(int i = 0;i < 10;i++) {
System.out.println("hello "+Thread.currentThread().getName());
}
}
}
/**
* step 1:写一个Runnable接口的实现类
*/
class MyRunnable implements Runnable {
/**
* step 2:实现Runnable接口run()
*/
@Override
public void run() {
for(int i = 0;i < 10;i++) {
System.out.println("hello "+Thread.currentThread().getName());
}
}
}
运行结果
2 线程参数传递
例3.在实现类或继承类中写局部变量,通过有参构造、setget方式获取参数。
代码
package com.whl.thread;
public class TestThread3 {
public static void main(String[] args) {
/**
* step 3:创建线程,创建实现类中传递实参
*/
Thread t1 = new Thread(new MyRunnable2(23));
t1.start();
int i = 6;
while(i-- > 0){
System.out.println(Thread.currentThread().getName());
}
}
}
class MyRunnable2 implements Runnable {
/**
* step 1:在实现类中定义局部变量
*/
private int age