关于java:java线程学习记录一

9次阅读

共计 1951 个字符,预计需要花费 5 分钟才能阅读完成。

java 中的线程应用

线程的定义

cpu 调度的最小单位,一个过程往往由一个或多个线程组成,线程中的通信容易同步简单,线程解体可能会影响整个程序的稳定性,可靠性低。

java 中创立线程的形式

继承 Thread

案例

public class Demo01 {
    // 继承 Thread 类
    public static class MyThread extends Thread{
        // 重写 run 办法
        @Override
        public void run() {System.out.println("MyThread");
        }
    }
    public static void main(String[] args) {
        // 实现
        Thread th=new MyThread();
        // 启动
        th.start();}
    
}

启动过程 :创建对象后,线程变成新建态,当调用 start 办法线程进入就绪态,取得 cpu 使用权运行后,线程进入运行态,执行实现后线程死亡。
异样剖析:反复调用 start 则会抛出异样

实现 Runnable 接口

JDK 源码

@FunctionalInterface
public interface Runnable {public abstract void run();
}

案例

public class Demo02 {
    // 实现 Runnable 接口
    public static class MyThread implements Runnable{
        // 实现 run 办法
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("MyThread");
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread th=new Thread(new MyThread());
        th.start();}
    
}

Thread 源码剖析

JDK 源码

// Thread 类源码
// ⽚段 1 - init ⽅法
private void init(ThreadGroup g, Runnable target, String name,
 long stackSize, AccessControlContext acc,
boolean inheritThreadLocals)

// ⽚段 2 - 构造函数调⽤ init ⽅法
public Thread(Runnable target) {init(null, target, "Thread-" + nextThreadNum(), 0);
}

// ⽚段 3 - 使⽤在 init ⽅法⾥初始化 AccessControlContext 类型的公有属性
this.inheritedAccessControlContext =
 acc != null ? acc : AccessController.getContext();
 
// ⽚段 4 - 两个对⽤于⽀持 ThreadLocal 的公有属性
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
                      

init 办法中参数剖析
ThreadGroup g:线程组,指定改线程归属于哪个线程组
Runnable target:执行的工作
String name:线程名
acc:⽤于初始化公有变量 inheritedAccessControlContext。
inheritThreadLocals:可继承的 ThreadLocal

罕用构造方法

// 创立一个线程,参数能够是一个实现 Runnable 接口的类
Thread(Runnable target)
// 创立一个指定线程名的线程
Thread(Runnable target,String name)

Thread 的罕用办法

currentThread():动态⽅法,返回对以后正在执⾏的线程对象的引⽤。
start():开始执行线程的办法,java 虚拟机调用线程中的 run 办法。
sleep:静态方法,让线程睡眠,工夫单位是毫秒,不会放弃对象锁。
yield:中文意思放弃,会让线程放弃 cpu 使用权,从运行态转换为就绪态,这⾥须要留神的是,就算以后线程调⽤了 yield()
⽅法,程序在调度的时候,也还有可能持续运⾏这个线程的。
join:使以后线程期待指定线程执行完结之后执行,外部调用 Object 的 wait 办法实现。

Thread 类与 Runnable 接口的比拟

Runnable 属于接口,应用起来比 Thread 更加灵便。
Runnable 更加合乎面向对象,将线程进行独自的封装。
Runnable 接口升高了线程对象和线程工作的耦合性。
Runnable 没有 Thread 那么多的办法,更为轻量。
在应用时 Runnable 接口的优先级更高。

正文完
 0