1.线程的创建
线程的创建是多线程的第一步,同时其也有多种不同的创建方法常见的方法有以下五种:
1.继承Thread类
class MyThread extends Thread{
@Override
public void run() {
}
}
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new MyThread();
}
2.实现Runnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
}
}
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
}
}
3.匿名继承Thread
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(){
@Override
public void run() {
super.run();
}
};
}
}
4.匿名实现Runnable
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
}
});
}
}
5.lambda表达式
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
});
}
}
当然在这些方法中比较推荐的是实现接口来创建,因为java中是单继承但允许实现多个接口,如果继承了Thread那么就不能继承其他类,灵活性就降低了。
2.线程的中断
java中为线程的中断的方法就是interrupt(),但是判断线程是否是中断状态java提供了两种方法
1.interrupted()
该方法是测试当前线程是否是已经处于中断状态,执行后具有将状态标志位清楚为false的功能。
public class Demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
for(int i = 0; i < 5000; i++){
}
});
t1.start();
t1.interrupt();
System.out.println("线程是否停止" + t1.interrupted());
System.out.println("线程是否停止" + t1.interrupted());
}
}
有上诉代码及结果可知,该方法中所说的当前线程指的是main线程,因为其在main中被调用,如果其在其他线程中被调用则代表那个线程的状态。
public class Demo3 {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("线程是否停止" + Thread.interrupted());
System.out.println("线程是否停止" + Thread.interrupted());
}
}
如图所示,上诉代码可使main线程停止当是第二个打印确实false则可知该方法有清除标志状态的功能
2.isInterrupted()
测试线程Thread对象是否是中断状态,当不清除状态标志。
public class Demo3 {
public static void main(String[] args) throws InterruptedException {
MyThread t1 = new MyThread();
t1.start();
t1.interrupt();
System.out.println("线程是否停止" + t1.isInterrupted());
System.out.println("线程是否停止" + t1.isInterrupted());
}
}
3.线程的等待
线程的等待使用wait()方法,其作用是让当前线程进入阻塞队列等待,等待过程中可用notify()方法唤醒,不过如果阻塞队列中有大于1个线程在等待,那么notify()方法 的唤醒哪个线程是不确定的。
并且不管是wait()还是notify()都必须在锁范围内使用,因为wait()方法的使用要释放当前的锁资源进入阻塞队列
4.线程的休眠
线程的休眠使用sleep()方法来实现,不过该方法在指定睡眠时间结束前不能主动被唤醒与wait()能被主动唤醒有一定的区别。