多线程 一 基础认识。

69 阅读1分钟

main 用户线程。 gc 回收线程。

1 how to thread

三种方式
  1. 继承 thread
  2. 实现 Runable interaface
  3. 实现 Callable 接口 (先了解)

method 1

public class MyThread extends Thread
{

    @Override
    public void run()
    {
        for xx
    
    }
    
    public static void main()
    {
        MyThread t1 = new MyThread();
        
        t1.start();  //会并发。
        
        for xx  //xx
    }
    
}

method 2 implement runable

MyClass = new Xxx();
new Thread(MyClass).start()

method 3 callable

如图,了解即可。 实现 call 方法。 用法,如图。 image.png

差别,多了返回值,可以抛出异常。 用法略麻烦,用服务。

2 mult thread op one obj

多个线程操作同一个资源是,会不安全。 image.png

3 static proxy

正是对象和代理对象,实现同一个接口。 代理对象,代理真实角色。

new Thread( obj ).start();

new Thread( ()=> System.out.printLn("I love u")).start();