线程基本方法
1.创建线程
1.1 直接继承Thread类
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello world");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
1.2实现Runnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
while(true){
System.out.println("hello t");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1.3匿名内部类创建Thread子类对象
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("使用匿名类创建 Thread 子类对象");
}
};
t1.start();
}
1.4匿名内部类创建Runnable子类对象
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("使用匿名类创建 Runnable 子类对象");
}
});
1.5 lambda表达式创建Runnable子类对象(最多使用)
Thread t= new Thread(()->{
while(true){
System.out.println("Hello lambda");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
2.线程启动
Thread对象.start()
创建好一个线程并重写run()方法之后该如何启动调用线程呢?
run()方法就像一个指令清单,我们把这个线程需要做的事情写在run()里面,然后使用start()来使它动起来,开始执行我们写好的指令。
run方法的作用是描述线程具体要执行的任务;
start方法的作用是去申请系统线程;
若主动调用run方法,跟调用普通方法一样,正常执行一次;
start调用方法后, start方法内部会调用Java 本地方法(封装了对系统底层的调用)真正的启动线程,并执行run方法中的代码,run 方法执行完成后线程进入销毁阶段。
3.线程中断
3.1定义一个共享标记
public class ThreadDemo8 {
public static boolean isQuit=false;
public static void main(String[] args) {
Thread t=new Thread(()->{
while(!isQuit){
System.out.println("haha");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程终止");
});
t.start();
try {
Thread.sleep(3000
);
} catch (InterruptedException e) {
e.printStackTrace();
}
isQuit=true;
}
此处我们可以将标记定义为类成员静态变量,因为lambda表达式会出现变量捕捉问题。 或者使用volatile关键字修饰。
3.2使用inderrupt()通知
Thread t=new Thread(()->{
//currentThread 是获取到当前线程实例
//currentThread 在此处获得t
//
while (!Thread.currentThread().isInterrupted()){
System.out.println("123");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// break;//显式结束循环
}
}
});
t.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
4.线程等待
.join()方法
Counter counter =new Counter();
Thread t1=new Thread(()->{
for (int i = 0; i < 50000; i++) {
counter.add();
}
});
Thread t2=new Thread(()->{
for (int i = 0; i < 50000; i++) {
counter.add();
}
});
t1.start();
t2.start();
//等待两个线程结束
t1.join();
t2.join();
System.out.println(counter.get());
5.线程休眠
通过.sleep()方式使进程进入休眠状态
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
6.获取线程实例状态
New 线程还没被创建出来,只是有一个Thread对象
RANNABLE 就绪状态{正在运行;随时准备运行}
TIMED_WAITING 指定时间等待 》sleep()方法
BLOCKED 表示等待锁出现的状态
WAITING 使用wait方法出现的状态
TERMIMATED 系统中的线程已经执行完了,只剩Thread对象还在
hread t=new Thread(()->{
while(true){
// System.out.println("hello");
}
});
//获取当前线程状态
System.out.println(t.getState());
volatile关键字,线程安全