Java多线程
Posted 保护眼睛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程相关的知识,希望对你有一定的参考价值。
Java多线程
Java多线程
线程的创建
1.继承Thread
2.实现Runnable
3.实现Callable
使用继承Thread类来开发多线程的应用程序在设计上是有局限性的,因为Java是单继承。
继承Thread类
public class ThreadDemo1 {
// 继承Thread类 写法1
static class MyThread extends Thread{
@Override
public void run() {
//要实现的业务代码
}
}
// 写法2
Thread thread = new Thread(){
@Override
public void run() {
//要实现的业务代码
}
};
}
实现Runnable接口
//实现Runnable接口 写法1
class MyRunnable implements Runnable{
@Override
public void run() {
//要实现的业务代码
}
}
//实现Runnable接口 写法2 匿名内部类
class MyRunnable2 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//要实现的业务代码
}
});
}
}
实现Callable接口(Callable + FutureTask 创建带有返回值的线程)
package ThreadDeom;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* user:ypc;
* date:2021-06-11;
* time: 17:34;
*/
//创建有返回值的线程 Callable + Future
public class ThreadDemo2 {
static class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 0;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建Callable子对象
MyCallable myCallable = new MyCallable();
//使用FutureTask 接受 Callable
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
//创建线程并设置任务
Thread thread = new Thread(futureTask);
//启动线程
thread.start();
//得到线程的执行结果
int num = futureTask.get();
}
}
也可以使用lambda表达式
class ThreadDemo21{
//lambda表达式
Thread thread = new Thread(()-> {
//要实现的业务代码
});
}
Thread的构造方法
线程常用方法
获取当前线程的引用、线程的休眠
class Main{
public static void main(String[] args) throws InterruptedException {
Thread.sleep(1000);
//休眠1000毫秒之后打印
System.out.println(Thread.currentThread());
System.out.println(Thread.currentThread().getName());
}
}
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-11;
* time: 18:38;
*/
public class ThreadDemo6 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程的ID:" + Thread.currentThread().getId());
System.out.println("线程的名称:" + Thread.currentThread().getName());
System.out.println("线程的状态:" + Thread.currentThread().getState());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程一");
thread.start();
Thread.sleep(100);
//打印线程的状态
System.out.println("线程的状态:"+thread.getState());
System.out.println("线程的优先级:"+thread.getPriority());
System.out.println("线程是否存活:"+thread.isAlive());
System.out.println("线程是否是守护线程:"+thread.isDaemon());
System.out.println("线程是否被打断:"+thread.isInterrupted());
}
}
线程的等待
假设有一个坑位,thread1 和 thread2 都要上厕所。一次只能一个人上,thread2只能等待thread1使用完才能使用厕所。就可以使用join()方法,等待线程1执行完,thread2在去执行。👇
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 10:48;
*/
public class ThreadDemo13 {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"🚾");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"出来了");
}
};
Thread t1 = new Thread(runnable,"thread1");
t1.start();
//t1.join();
Thread t2 = new Thread(runnable,"thread2");
t2.start();
}
}
没有join()显然是不行的。加上join()之后:
线程的终止
1.自定义实现线程的终止
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 9:59;
*/
public class ThreadDemo11 {
private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (!flag){
System.out.println("我是 : " + Thread.currentThread().getName() + ",我还没有被interrupted呢");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("我是 "+Thread.currentThread().getName()+",我被interrupted了");
}
},"thread");
thread.start();
Thread.sleep(300);
flag = true;
}
}
2.使用Thread的interrupted来中断
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 9:59;
*/
public class ThreadDemo11 {
// private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()){
System.out.println("我是 : " + Thread.currentThread().getName() + ",我还没有被interrupted呢");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// e.printStackTrace();
break;
}
}
System.out.println("我是 "+Thread.currentThread().getName()+",我被interrupted了");
}
},"thread");
thread.start();
Thread.sleep(300);
thread.interrupt();
// flag = true;
}
}
3.Thraed.interrupted()方法和Threaed.currentThread().interrupt()的区别
Thread.interrupted()方法第一次接收到终止的状态后,之后会将状态复位,Thread.interrupted()是静态的,是全局的。Threaed.currentThread().interrupt()只是普通的方法。
Thraed.interrupted()方法
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 10:32;
*/
public class ThreadDemo12 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() ->{
for (int i = 0; i < 10; i++) {
System.out.println(Thread.interrupted());
}
});
thread.start();
thread.interrupt();
}
}
Threaed.currentThread().interrupt()
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 10:32;
*/
public class ThreadDemo12 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() ->{
for (int i = 0; i < 10; i++) {
// System.out.println(Thread.interrupted());
System.out.println(Thread.currentThread().isInterrupted());
}
});
thread.start();
thread.interrupt();
}
}
yield()方法
让出CPU的执行权
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 11:47;
*/
public class ThreadDemo15 {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
Thread.yield();
System.out.println("thread1");
}
});
thread1.start();
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println("thread2");
}
});
thread2.start();
}
}
线程的状态
打印出线程的所有的状态,所有的线程的状态都在枚举中。👇
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 11:06;
*/
public class ThreadDemo14 {
public static void main(String[] args) {
for (Thread.State state: Thread.State.values()) {
System.out.println(state);
}
}
}
NEW 创建了线程但是还没有开始工作
RUNNABLE 正在Java虚拟机中执行的线程
BLOCKED 受到阻塞并且正在等待某个监视器的锁的时候所处的状态
WAITTING 无限期的等待另一个线程执行某个特定操作的线程处于这个状态
TIME_WAITTING 有具体等待时间的等待
TERMINATED 已经退出的线程处于这种状态
package ThreadDeom;
/**
* user:ypc;
* date:2021-06-12;
* time: 11:06;
*/
class TestThreadDemo{
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out<以上是关于Java多线程的主要内容,如果未能解决你的问题,请参考以下文章