首先,先看看多线程最基础应该掌握的几个方面:
1.使用线程的方式一个有三种:
(1)、继承Thread类
(2)、实现接口Runnable
(3)、实现Callable(不推荐,不实用)
接下看具体的代码实现
// 继承Thread实现多线程
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i<10; i++){
System.out.println("MyThread");
}
}
}
//实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("MyRunnable");
}
}
}
//测试类
public class Test {
public static void main(String[] args) {
//创建线程对象
MyThread myThread = new MyThread();
//开启线程
myThread.start();
//创建MyRunnable对象
MyRunnable myRunnable = new MyRunnable();
//创建Thread对象,传入Runnable对象
Thread thread1 = new Thread(myRunnable);
//开启线程
thread1.start();
}
}
实现Runnable的两种简单方法:
(1)、使用匿名内部类
public class Test {
public static void main(String[] args) {
MyRunnable1 myRunnable = new MyRunnable1();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyRunnable1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
(2)、使用lambda表达式
public class Test2 {
public static void main(String[] args) {
new Thread(()->{
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}).start();
}
}
2.线程的状态
(1)、创建状态:实例化一个线程对象,但未启动
(2)、就绪状态:start之后,进入线程池等待抢占 CPU 资源。
(3)、运行状态:抢占到cpu资源后,在规定时间内执行线程任务
(4)、阻塞状态:线程遇到其他情况,释放cpu资源
(5)、终止状态:线程结束
3.线程调度
(1)、线程休眠
线程调用sleep(),线程进入阻塞状态,让当前的线程暂停
public class Test2 {
public static void main(String[] args) {
new Thread(()->{
for (int i = 0; i < 100; i++) {
if(i==10){
try {
//参数为毫秒,1000ms=1s
//注意捕获异常
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
}
}).start();
}
}
(2)、线程合并
线程调用join(),将两个线程任务合并为一个
public class Test2 {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
for (int i = 0; i < 200; i++) {
System.out.println(i + "--------------ABC");
}
});
thread1.start();
Thread thread2 = new Thread(()->{
for (int i = 0; i < 200; i++) {
System.out.println(666);
}
});
thread2.start();
for (int i = 0; i < 100; i++) {
if(i == 10){
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i + "++++++++++++++++main");
}
}
}
运行结果:
(3)、线程礼让
线程调用yield(),在某个特定的时间点上释放cpu资源,但是只释放一瞬间
public class Test3 {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
for (int i = 0; i < 100; i++) {
if (i == 7) {
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + "------" + i);
}
},"线程甲");
thread1.start();
Thread thread2 = new Thread(()->{
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "------" + i);
}
},"线程乙");
thread2.start();
}
}
运行结果: