1、线程创建
博主另外整理过了,链接:http://t.csdn.cn/DeRKj
2、线程中断
- private static boolean isQuit;
- //标记
-
- public static void main(String[] args) {
- Thread t = new Thread(()-> {
- while(!isQuit) {
- System.out.println("thread");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- System.out.println("线程t执行结束");
- });
- t.start();
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- isQuit=true;
- System.out.println("设置让t线程结束");
- }
- public static void main(String[] args) {
- Thread t = new Thread(()-> {
- while(!Thread.currentThread().isInterrupted()) {
- //currentThread()是Thread类的静态方法
- //通过这个方法,就可以拿到当前线程的实例
- //isInterrupted()这个方法就是在判定标志位
- System.out.println("thread");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- //throw new RuntimeException(e);
-
- //方式一:立即结束线程
- break;
-
- //方式二:线程继续执行,不管
-
- //方式三:稍后处理,例:
- //Thread.sleep(1000);
- //break;
- }
-
- }
- System.out.println("线程t执行结束");
- });
- t.start();
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- t.interrupt();
- //在主线程中,设置t.interrupt()来中断这个线程,设置标志位为true
- System.out.println("设置让t线程结束");
- }
3、线程等待
由于线程之间的调度顺序是不确定的,因此通过特殊操作,对线程的执行顺序,作出干预,例如:
通过join()方法,控制线程之间的结束顺序
在main中调用join:让main线程阻塞等待,等到t执行完了,main才继续执行
- public static void main(String[] args) {
- Thread t = new Thread(()-> {
- int i=0;
- while( i<3) {
- System.out.println("Thread");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- i++;
- }
- });
- t.start();
- System.out.println("main线程join之前");
- try {
- t.join();
-
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- System.out.println("main线程结束join之后");
- }
注:Java中的多线程方法,只要这个方法会阻塞,都可 能抛出InterrupttedException异常
输出:
注:有人会问,线程之间的调度顺序不是不确定的吗?那为什么这里是先打印“ main线程join之前”,再打印“Thread"?
解答:首先,你的想法是对的,确实先打印哪一个就是不确定,但即使如此,大概率还是先打印main.因为在start之后,内核要创建线程(有开销),start调用的时候,为了执行新线程的代码,需要先做一些准备工作,因此导致大概率先打印“main线程join之前”,但并非百分之分。
另外join也又另外两种带参数的,可以控制阻塞时长:

4、线程休眠
上述的例子中,我们会看到有一个sleep方法,就是线程休眠,代码中是休眠一千毫秒的,但实际上并非如此,而是大于等于1000(因为线程的调度是不可控的)
5、获取线程实例
方法:
| 方法 | 说明 |
| public static Thread currentThread(); | 返回当前对象的引用 |
例:
- Thread thread = Thread.currentThread();
- System.out.println(thread.getName());