JDK8源码阅读笔记--------java.lang.Thread

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

*The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
*All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows:

class PrimeThread extends Thread {
           long minPrime;
           PrimeThread(long minPrime) {
               this.minPrime = minPrime;
           }
  
           public void run() {
               // compute primes larger than minPrime
                . . .
           }
       }

The following code would then create a thread and start it running:
       PrimeThread p = new PrimeThread(143);
       p.start();
The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following:

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following:

 class PrimeRun implements Runnable {
           long minPrime;
           PrimeRun(long minPrime) {
               this.minPrime = minPrime;
           }
  
           public void run() {
               // compute primes larger than minPrime
                . . .
           }
       }

The following code would then create a thread and start it running:
       PrimeRun p = new PrimeRun(143);
       new Thread(p).start();
   
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

 大意为:

线程是程序中的执行线程。Java虚拟机允许应用程序同时运行多个执行线程。每个线程都有优先级。优先级较高的线程优先于优先级较低的线程执行。每个线程可能被标记为守护进程,也可能不被标记为守护进程。当在某个线程中运行的代码创建一个新的线程对象时,新线程的优先级最初设置为与创建线程的优先级相等,并且当且仅当创建线程是一个守护线程时,它就是一个守护线程。以及创建线程的两种方式。为了便于识别,每个线程都有一个名称。多个线程可能具有相同的名称。如果在创建线程时没有指定名称,则会为其生成一个新名称。

Thread实现Runnable接口

1.线程优先级

从1-10一次增大,默认5:

/**
  * The minimum priority that a thread can have.
  */
 public final static int MIN_PRIORITY = 1;

/**
  * The default priority that is assigned to a thread.
  */
 public final static int NORM_PRIORITY = 5;

 /**
  * The maximum priority that a thread can have.
  */
 public final static int MAX_PRIORITY = 10;

2.静态方法 currentThread()

Returns a reference to the currently executing thread object.

Thread.currentThread();获得当前线程对象。

3.静态方法 yield()

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

给调度器的提示,即当前线程愿意放弃当前对处理器的使用。调度程序可以忽略这个提示。

Yield是一个启发式的尝试,旨在改进线程之间的相对进程,否则会过度使用CPU。它的使用应该与详细的分析和基准测试相结合,以确保它确实具有预期的效果。

很少使用这种方法。它可能对调试或测试很有用,因为它可能会因为竞争条件而帮助重现bug。在设计并发控制结构(比如java.util.concurrent中的结构)时,它可能也很有用。

4.静态:sleep(long millis)、sleep(long millis, int nanos)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

线程睡眠指定毫秒数,但是不放弃监视器的所有权。

5.有(无)参构造方法:

线程名:默认Thread-int,可以指定

target:比如某类(ARunnable)实现runnable接口,则可以new Thread(new ARunnable()).start。

stackSize:设置新线程堆栈内存,0表示忽略。

6.被synchronized修饰 start():

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

大意是:是当前线程开始执行。虚拟机调用线程的run方法。结果是两个线程同时运行:当前线程(从调用开始方法返回)和另一个线程(执行其运行方法)。多次启动线程是不合法的。特别是,线程一旦完成执行,可能就不会重新启动。

7.run():

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Subclasses of Thread should override this method.

如果这个线程是使用一个单独的Runnable run对象构造的,则调用该Runnable对象的run方法;否则,此方法不执行任何操作并返回。线程的子类应该重写这个方法。

8.interrupt()

中断线程。

9.isInterrupted()

Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.

判断线程是否被中断了。

public static void main(final String[] args) {

        Thread thread = new Thread();
        //开启线程
        thread.start();
        //中断线程
        thread.interrupt();
        //测试是否中断
        boolean interrupted = thread.isInterrupted();
        System.out.println(interrupted);//true
    }

10.isAlive()

Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

11.setPriority(int newPriority)、getPriority()

设置(获取)线程的优先级。

12.setName(String name)、getName()

设置、获取线程名。

13.被synchronized修饰join(long millis),join()--实际是join(0)

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

等待线程死亡的时间最多为千分之一毫秒。超时为0意味着永远等待。这个实现使用这个循环。基于此条件的等待调用。当线程终止此操作时。调用notifyAll方法。建议应用程序不要在线程实例上使用wait、notify或notifyAll。

原理是join方法内部调用object类的wait方法。

14.setDaemon(boolean on)

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be invoked before the thread is started.

将该线程标记为守护进程线程或用户线程。当惟一运行的线程都是守护进程线程时,Java虚拟机将退出。必须在启动线程之前调用此方法。

如果该线程isAlive(),不能设置为守护线程。

15.getContextClassLoader()

Returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.
If a security manager is present, and the invoker's class loader is not null and is not the same as or an ancestor of the context class loader, then this method invokes the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to verify that retrieval of the context class loader is permitted.

获取该线程的上下文类加载器。下文类加载器是由线程的创建者提供的,以便在加载类和资源时由该线程中运行的代码使用。如果不设置,默认是父线程的类加载器。

16.setContextClassLoader(ClassLoader cl)

Sets the context ClassLoader for this Thread. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader, through getContextClassLoader, to code running in the thread when loading classes and resources.

17.状态枚举类State

包含new,runnable,blocked,waiting,timed_waiting,terminated.

猜你喜欢

转载自blog.csdn.net/weixin_39035120/article/details/84344112
今日推荐