o(* ̄︶ ̄*)o

  博客园  :: 首页  ::  :: 联系 :: 订阅 订阅  :: 管理

Java线程

口诀:单继承,双实现,重写run与call。5调度,6状态,5通信,还有一个ThreadLoacal。

关键字:extends(继承)、implememts(实现)、synchronized(方法、代码块)、volatile(成员变量)

 

一、线程创建

1.继承Thread类

public class tool extends Thread{
    //重写Thread中的接口
    @Override
    public void run(){
        System.out.println("这是一个子线程");
    }


    //调用
    public static void main(String args[]){
        //线程初始状态
        tool p = new tool();
        //线程运行/就绪状态
        p.start(); 
    }
}

2.实现Runnable接口

public class tool implements Runnable{
    //重写接口Runnable中的方法
    @Override
    public void run(){
        System.out.println("这是一个子线程");
    }

    //调用
    public static void main(String args[]){
        tool p = new tool();
        //由新线程来替代tool类运行
        new Thread(p).start(); 
    }
}

3.实现Callable接口

  特点:主线程可以获取子线程执行结果,需要指定返回类型。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//int类型
class TestTaskNum implements Callable<Integer>{
    public Integer call() throws Exception{
        //返回执行结果
        return 9999;
    }
}

//字符串类型
class TestTask implements Callable<String>{
    public String call() throws Exception{
        //返回执行结果
        return "子线程果实";
    }    
}

  //伪代码实现
  public static void main(String args[]){
        //创建异步task托管Callable
        FutureTask<String> task1 = new FutureTask<>(new TestTask());
        
        //启动线程
        new Thread(task1).start(); 
        
        try {
            String str = task1.get();
            System.out.println(str);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }catch(ExecutionException e) {
            e.printStackTrace();
        }
        
        //创建异步task托管Callable
        FutureTask<Integer> task2 = new FutureTask<>(new TestTaskNum());
        
        //启动线程
        new Thread(task2).start(); 
        
        try {
            int value = task2.get();
            System.out.println(value);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }catch(ExecutionException e) {
            e.printStackTrace();
        }
        
    }

 

二、线程调度方法

  • 等待(wait、join)
  • 通知(notify、notifyAll)
  • 优先权(yield)
  • 中断(interrupt、isinterrupted、interrupted)
  • 休眠(sleep)

三、线程状态

1.初始状态,未start

2.运行状态

3.等待状态

4.超时等待

5.阻塞状态

6.终止状态

四、线程间通信

1.volatile(同步变量值)和synchronized(保护方法块、函数,同一时间只执行一次)关键字

2.等待/通知机制(wait、join、notify/notifyAll等方法使用)

3.管道输入流、输出流(字节两种,字符两种)

4.使用Thread.join()    

5.使用ThreadLocal(线程本地变量,key-value)

五、ThreadLoacl的使用

  1.使用示例

  2.实现原理

  3.使用ThreadLocal内存怎么泄露的

  4.ThreadLocalMap结构,怎么解决Hash冲突的,扩容机制怎么实现的

  5.父子线程数据共享:InheritableThreadLocal类

六、指令重排顺序(3种)

  源码  -->    1.编译器(优化重排序)  -->    2.指令级(并行重排序)    -->    3.内存(系统重排序)    -->    最终执行的指令序列

  单例示例如下(图片来源网络)

 

posted on 2024-04-28 12:45  熊本熊の熊  阅读(7)  评论(0)    收藏  举报