目录
注意:如果说thread线程是死锁或者是一个已经损毁的程序,这样join()方法后main会一直等待下去,这儿THread提供了另一种join方法。具体代码如下
一.线程的创建
线程的创建有5种方式
1.自己定义一个类并继承Thread创建并重写run方法
class MyThread extends Thread{
public void run(){
System.out.println("第一种创建线程的方法");
}
}
public class Demo2 {
MyThread thread1=new MyThread();
}
2.创建一个类实现Runnable接口,重写run方法后将对象传参给Thread实例
public class Demo3 {
Thread thread2=new Thread(new MyRunnable());
}
class MyRunnable implements Runnable{
public void run(){
System.out.println("第二种创建现成方法");
}
}
3.通过匿名内部类Thread来实现
public class Demo4 {
Thread thread3=new Thread(){
public void run(){
System.out.println("第三种创建线程的方法");
}
};
}
4.通过匿名Runnable接口实现
public class Demo5 {
Thread thread4=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("第四种创建线程的方式");
}
});
}
5.通过lamda表达式创建线程
public class Demo6 {
Thread thread4=new Thread(()->{
System.out.println("这是第五种创建线程的方式");
} );
}
二.线程中断
线程中端有两种线程中断方法
1.通过给定义个while循环来判断,具体代码如下
public class Solution{
public static void main(String args[]){
boolean isTrue=true;
Thread thread =new Thread(()->{
while(isTrue){
System.out.println("程序正在进行");
}
});
thread.start();
try{
Thread.sleep(5000)
}catch(InterruptedException e){
e.printStackTrace
}
isTrue=false;
System.out.println("程序已经被终止");
}
}
2.通过Thread类的类方法来实现,具体代码如下:
public class Solution{
public static main(String[] args[]){
Thread thread =new Thread(()->{
while(Thread.CurrentThread().isInterrupted()){
System.out.println("程序正在进行");
}
});
thread.start();
try{
Thread.sleep(5000)
}catch(InterruptedException e){
e.printStackTrace
}
thread.isInterrRupted();
System.out.println("程序已经终止");
}
}
三.线程等待
线程等待利用到了Thread中的join方法,具体代码如下
public class Solution{
public static main(String[] args[]){
Thread thread =new Thread(()->{
while(Thread.CurrentThread().isInterrupted()){
System.out.println("程序正在进行");
}
});
thread.start();
try{
Thread.sleep(5000)
}catch(InterruptedException e){
e.printStackTrace
}
thread.join();//此时要等待thread运行结束才能继续主线程
System.out.println("threadd已经运行结束");
}
}
注意:如果说thread线程是死锁或者是一个已经损毁的程序,这样join()方法后main会一直等待下去,这儿THread提供了另一种join方法。具体代码如下
thread.join(5000);
//此时主线程只会等待thread线程5s,不管是否已经执行完毕,主线程都将开始继续运行
四.线程休眠
以上便是线程休眠。
五.获取当前线程实例
public class Solution{
public static void main(String[] args)
{
Thread thread=Thread.CurrentThread();
System.out.println(thread.getName());
}
//获取当前线程实例