Java并发编程(一)

2023-02-06 18:21:48 浏览数 (1)

昨天忘关电脑了,今天极其极其慢,开了没几个应用,一卡一卡,同步打开几个笔记都卡到不能加载,平时上网课吧,小伙伴说不系统,那根据网课的大纲白*自己找资料不香么?大纲太大了,放在最后。

1.进程与线程的关系

进程是指运行中的应用程序,每个进程都有自己独立的地址空间(内存空间)。

线程则是进程中执行运算的最小单位,即执行处理机调度的基本单位。

2.内存与线程

内存管理与线程进程组成内存分配,系统不会为线程分配内存

3.JDK工具观察线程

代码层面:

JMX ThreadMXBean threadInfo()

JDK工具:Jconsole

4.线程创建方法以及线程状态

JDK1.5以前1:继承Thread类,实现Runable接口,JDK1.5以后新增2:实现Callable接口,线程池中获得。

线程状态:6种,看源码

代码语言:javascript复制
 * A thread state.  A thread can be in one of the following states:
 * 一个线程,有以下几种状态
 * <ul>
 * <li>{@link #NEW}<br>
 * ①未启动的线程状态   new
 *     A thread that has not yet started is in this state.
 *     </li>
 * <li>{@link #RUNNABLE}<br>
 * ②在jvm中执行的线程状态  runnable
 *     A thread executing in the Java virtual machine is in this state.
 *     </li>
 * <li>{@link #BLOCKED}<br>
 * ③一个线程被阻塞,等待监控锁的线程状态  blocked
 *     A thread that is blocked waiting for a monitor lock
 *     is in this state.
 *     </li>
 * <li>{@link #WAITING}<br>
 * 	④一个线程  为了永久等待另一个线程特定的操作的线程状态  waiting
 * 翻译后通顺点:无限等待另一个线程的线程执行特定的操作处于此状态
 *     A thread that is waiting indefinitely for another thread to
 *     perform a particular action is in this state.
 *     </li>
 * <li>{@link #TIMED_WAITING}<br>
 *   ⑤ 一个线程  等待另一个线程执行特定的操作的等待时间内的线程状态   timed_waiting
 *     正在等待另一个线程执行某个操作的线程在指定的等待时间内处于这种状态
 *     A thread that is waiting for another thread to perform an action
 *     for up to a specified waiting time is in this state.
 *     </li>
 * <li>{@link #TERMINATED}<br>
 * ⑥一个线程已经被退出的状态   终止  terminated
 *     A thread that has exited is in this state.
 *     </li>
 * </ul>
 *
 * <p>
 * 在给定的时间点上,线程只能处于一种状态。这些状态是虚拟机状态,不反映任何操作系统线程状态
 * A thread can be in only one state at a given point in time.
 * These states are virtual machine states which do not reflect
 * any operating system thread states.
 *
 * @since   1.5   
 * @see #getState
 */

5.Join方法解析

源码:

代码语言:javascript复制
public final void join() throws InterruptedException {
    join(0);
}
Waits for this thread to die等待线程死亡
join(0)实现
代码语言:javascript复制
public final synchronized void join(long millis)
throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        通常调用都是==0
        判断当前线程状态
        while (isAlive()) {
            等待直到被唤醒
/**
 * Causes the current thread to wait until either another thread invokes the
 * {@link java.lang.Object#notify()} method or the
 * {@link java.lang.Object#notifyAll()} method for this object, or a
 * specified amount of time has elapsed.
 */
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

6.Sleep方法

代码语言:javascript复制
Thread.sleep(0);
源码:
public static void sleep(long millis, int nanos)
throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis  ;
    }

    sleep(millis);
}

public static native void sleep(long millis) throws InterruptedException;
/**
if any thread has interrupted the current thread. The
*          <i>interrupted status</i> of the current thread is
*          cleared when this exception is thrown.
*/

线程进入睡眠状态

7.yield方法

代码语言:javascript复制
public static native void yield();
scheduler that the current thread is willing to yield  调度当前线程进入yield
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.

进入yield状态

8.线程中断方法

1.加开关

2.isInterrupted *.cpp是C的实现

中断仅仅是设置状态,而非中止线程

为什么放弃stop?防止死锁ddd

3.0说明Thread interrupt() isinterrupted()interrupted 的区别和含义

Thread.interrupt() 设置状态

isInterrupted() 判断 返回Boolean

interrupted 即判断又清除

9.线程安全问题是如何产生的?

多线程并发执行时,对共享内存中共享对象的属性发生修改时所导致的数据冲突问题,称之为线程安全问题

10.Synchronized关键字

1.synchronized是JVM层面实现的,java提供的关键字

2.synchronized不需要手动释放锁,底层会自动释放

3.synchronized等待不可中断,除非抛出异常或者执行完成

4.synchronized是非公平锁

5.synchronized不可绑定多个条件

代码语言:javascript复制
public class Demo {
       public void method() {
        synchronized (this) {
            System.out.println("synchronized ...");
        }
    }
}
代码语言:javascript复制
javap -c
Compiled from "Demo.java"
public class io.renren.controller.Demo {
  public io.renren.controller.Demo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public void method();
    Code:
       0: aload_0
       1: dup
       2: astore_1
       3: monitorenter
       4: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       7: ldc           #3                  // String Method 1 start
       9: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      12: aload_1
      13: monitorexit
      14: goto          22
      17: astore_2
      18: aload_1
      19: monitorexit
      20: aload_2
      21: athrow
      22: return
    Exception table:
       from    to  target type
           4    14    17   any
          17    20    17   any
}

monitorenter

monitorexit

synchronized通过监控对象来完成,本质是锁一个对象

同步方法

代码语言:javascript复制
public class Demo {
    public synchronized void method() {
        System.out.println("synchronized....");
    }
}

修饰方法与修饰代码块产生字节码不同

课程总纲实在太大上传不了...

代码语言:javascript复制
链接:https://pan.baidu.com/s/1zzRctyj9eRazAvlnRH-B2g
提取码:a7nb
jdk

0 人点赞