创建线程
1.继承Thread类重写run方法
class MyThread extends Thread{
public void run() {
System.out.println("hehe");
}
}
public class TherdDeom {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
}
}
2.实现Runnable,重写run
class MyRunnable implements Runnable{
public void run() {
System.out.println("haha");
}
}
public class TherdDeom {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
3.继承Thread类,匿名内部内
public static void main(String[] args) {
Thread t = new Thread() {
public void run(){
System.out.println("hello t");
}
};
t.start();
}
4.实现Runnable类,匿名内部内
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello t");
}
});
t.start();
}
5.lambda表达式
public static void main(String[] args) {
Thread t = new Thread( () -> {
System.out.println("hello t");
});
t.start();
}
休眠线程
Thread.sleep();
public static void main(String[] args) {
int val = 0;
Thread t = new Thread( () -> {
while(true) {
System.out.println("hello t"+ val);
val++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
这个代码是有问题的,原因是:lambda表达式可以访问外面的局部变量,这是变量捕获的规则,但要求捕获的变量必须是final或实际final(变量没有final修饰,代码中没有修改),这里的val++,导致的问题
解决方法:把val定义在lambda表达式中
获取线程实例
Thread.currentThread();
public static void main(String[] args) {
Thread t = new Thread( () -> {
System.out.println(Thread.currentThread().getName());
});
t.start();
}
中断线程
使用Thread类内置的标志位
isInterrupted();(获取当前线程标志位)默认 false
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread( () -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
});
t.start();
Thread.sleep(3000);
t.interrupt();
}
interrupt();作用
1.设置标位为true
2.如果该线程处于阻塞状态此时就会抛异常的方式,让线程立即唤醒
注意:当线程在sleep状态被唤醒,会自动把标志位置为false
抛了异常之后,while循环条件满足还继续执行t线程
等待线程
线程与线程之间是抢占式执行,我们不能确定那个线程先执行,我们可以使用join()
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread( () -> {
System.out.println("hello t");
});
t.start();
t.join();
System.out.println("hello main");
}
main线程调用t.join时如果t还在运行,main就阻塞等待,直到t执行完才能执行main线程