1.走近Java世界中的线程

(1)创建线程的两种构造器

  • Thread()
    定义Thread类的子类,覆盖run方法,并在该方法中实现线程任务处理逻辑
public class WelcomeApp {
    public static void main(String[] args) {
        // 创建线程
        Thread welcomeThread = new WelcomeThread();

        // 启动线程
        welcomeThread.start();

        // 输出“当前线程”的线程名称
        System.out.printf("1.Welcome! I'm %s.%n", Thread.currentThread().getName());
    }
}

// 定义Thread类的子类
class WelcomeThread extends Thread {

    // 在该方法中实现线程的任务处理逻辑
    @Override
    public void run() {
        System.out.printf("2.Welcome! I'm %s.%n", Thread.currentThread().getName());
    }
}
/*
1.Welcome! I'm main.
2.Welcome! I'm Thread-0.
 */
  • Thread(Runnable target)
    创建一个java.lang.Runnable接口的实例,并在该实例的run方法中实现任务处理逻辑,然后以该Runnable接口实例作为构造器的参数直接创建一个Thread类的实例。
public class WelcomeApp1 {

   public static void main(String[] args) {
       // 创建线程
       Thread welcomeThread = new Thread(new WelcomeTask());

       // 启动线程
       welcomeThread.start();
       // 输出“当前线程”的线程名称
       System.out.printf("1.Welcome! I'm %s.%n", Thread.currentThread().getName());
   }
}

class WelcomeTask implements Runnable {
   // 在该方法中实现线程的任务处理逻辑
   @Override
   public void run() {
       // 输出“当前线程”的线程名称
       System.out.printf("2.Welcome! I'm %s.%n", Thread.currentThread().getName());
   }
}
/*
1.Welcome! I'm main.
2.Welcome! I'm Thread-0.
*/

(2) 线程的属性

  • 编号(ID)
  • 名称(Name)
  • 线程类别(Daemon)
  • 优先级(Priority)
public class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    /* Reserved for exclusive use by the JVM, maybe move to FieldHolder */
    private long eetop;

    // thread id
    private final long tid;

    // thread name
    private volatile String name;

    // interrupt status (read/written by VM)
    volatile boolean interrupted;

    // context ClassLoader
    private volatile ClassLoader contextClassLoader;

    // inherited AccessControlContext, this could be moved to FieldHolder
    @SuppressWarnings("removal")
    private AccessControlContext inheritedAccessControlContext;

    // Additional fields for platform threads.
    // All fields, except task, are accessed directly by the VM.
    private static class FieldHolder {
        final ThreadGroup group;
        final Runnable task;
        final long stackSize;
        volatile int priority;
        volatile boolean daemon;
        volatile int threadStatus;
        boolean stillborn;

        FieldHolder(ThreadGroup group,
                    Runnable task,
                    long stackSize,
                    int priority,
                    boolean daemon) {
            this.group = group;
            this.task = task;
            this.stackSize = stackSize;
            this.priority = priority;
            if (daemon)
                this.daemon = true;
        }
    }
    private final FieldHolder holder;
    ...
    }

private static class FieldHolder是Java中Thread类中的一个私有静态嵌套类。它通常用于实现单例对象的"延迟初始化"模式。

该模式的思想是将对象的创建延迟到实际需要时,以节省资源并提高性能。在单例模式的情况下,这意味着单例实例在程序第一次请求它时才会被创建。

FieldHolder类用于将单例实例作为静态字段保存,并使用私有静态初始化块进行懒初始化。该块仅在第一次调用getInstance()方法时执行一次。getInstance()方法返回单例实例,该实例是通过调用外部类的私有构造函数创建的。

(3) 线程的常用方法

  • currentThread()
    @IntrinsicCandidate
    public static native Thread currentThread();
  • run()
    @Override
    public void run() {
        Runnable task = holder.task;
        if (task != null) {
            task.run();
        }
    }
  • start()
    public void start() {
        synchronized (this) {
            // zero status corresponds to state "NEW".
            if (holder.threadStatus != 0)
                throw new IllegalThreadStateException();
            start0();
        }
    }
  • join()
    public final void join(long millis) throws InterruptedException {
        if (millis < 0)
            throw new IllegalArgumentException("timeout value is negative");

        if (this instanceof VirtualThread vthread) {
            if (isAlive()) {
                long nanos = MILLISECONDS.toNanos(millis);
                vthread.joinNanos(nanos);
            }
            return;
        }

        synchronized (this) {
            if (millis > 0) {
                if (isAlive()) {
                    final long startTime = System.nanoTime();
                    long delay = millis;
                    do {
                        wait(delay);
                    } while (isAlive() && (delay = millis -
                             NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
                }
            } else {
                while (isAlive()) {
                    wait(0);
                }
            }
        }
    }
  • yield()
    public static void yield() {
        if (currentThread() instanceof VirtualThread vthread) {
            vthread.tryYield();
        } else {
            yield0();
        }
    }
  • sleep()
    public static void sleep(long millis) throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (currentThread() instanceof VirtualThread vthread) {
            long nanos = MILLISECONDS.toNanos(millis);
            vthread.sleepNanos(nanos);
            return;
        }

        if (ThreadSleepEvent.isTurnedOn()) {
            ThreadSleepEvent event = new ThreadSleepEvent();
            try {
                event.time = MILLISECONDS.toNanos(millis);
                event.begin();
                sleep0(millis);
            } finally {
                event.commit();
            }
        } else {
            sleep0(millis);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值