线程创建
public class Demo6 {
public static void main(String[] args) {
Thread t = new Thread(()->{
while(true){
System.out.println("hello Thread");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
创建一个线程的本质:创建出一个PCB,然后把这个PCB加入到对应链表中.
一个线程的创造要分为三步:
1.new一个新的Tread,就是创建一个新的线程对象.
2.用一个lambda方法创建一个匿名函数来覆写run方法,就是给线程提供一个指令清单.
3.最后通过调用start()方法使这个新的线程开始独立执行.(start的本质就是调用系统的api来完成线程创建的工作)
线程中断
什么是中断?当一个run执行完毕后就算中断了.我们可以做的就是加快这个run的过程.
有两种方法可以加快这一过程
-
通过共享的标记来进行沟通
public class Demo6 {
public static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while(!isQuit){
System.out.println("hello Thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(3000);
isQuit = true;
}
}
通过上图可以发现代码在执行一段时间后自动停止了.
我们通过设置一个标志位,通过改变这个标志位来使这个run能够提前执行完毕.
当线程执行到isquit=ture时另一线程的条件被改变使该线程提前结束.
-
调用interrupt()方法来通知
public class Demo7 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while(!Thread.currentThread().isInterrupted()){
System.out.println("hello Thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(3000);
t.interrupt();
}
}
Thread.currentThread()获取的是当前线程的对象. isInterrupted()在Thread对象内部,提供了一个标志位(Boolean)true线程结束,false线程不结束.
出现这一段报错是因为t线程正在sleep,然后被intrrupt打断了.在这个被打断的时候自动清除了前面的标志位.给程序猿提供了操作空间.如果想继续让线程结束直接在catch中加入break.
线程等待
public class Demo8 {
public static void main(String[] args) {
Thread a = new Thread(()->{
for (int i = 0; i < 5; i++) {
System.out.println("hello a");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a 线程结束了");
});
Thread b = new Thread(()->{
for (int j = 0; j < 3; j++) {
System.out.println("hello b");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b 线程结束了");
});
a.start();
b.start();
}
}
多个线程是并行执行的,具体的执行过程都是由操作系统负责调度的.操作系统调度线程的过程是随机的无法确定先后顺序.这个时候等待线程就可以帮助我们规划线程.
上述代码中有a,b两个线程,如果希望a先结束,b后结束,此时就可以在b的线程中调用a.join().此时a线程没有执行完,b线程进入了阻塞状态.给a线程留下执行时间,当a执行完成,b线程从阻塞状态中恢复,接着往后执行.