# multi-threaded **Repository Path**: JarryShu/multi-threaded ## Basic Information - **Project Name**: multi-threaded - **Description**: Java多线程 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-03-01 - **Last Updated**: 2024-03-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # java 多线程 ## 继承`java.lang.Thread`类,重写`run`方法 `java.lang.Thread`类实现`java.lang.Runnable`接口的`run`方法,`Thread`中源码如下 ```java public class Thread implements Runnable { /* What will be run. */ private Runnable target; /*中间大部分无关代码省略*/ @Override public void run() { if (target != null) { target.run(); } } } ``` ## 实现`java.lang.Runnable`接口的`run`方法 `Runnable`接口中仅有一个方法——`run` ```java @FunctionalInterface public interface Runnable { public abstract void run(); } ``` 所以在利用`Runnable`实现多线程的时候,我们要借助`Thread`类中的方法。 ```java /** * @param target 实现runnable接口的类实例 * @param name 自定义线程名 */ public Thread(Runnable target, String name) { init(null, target, name, 0); } ``` Thread方法中调用init方法,源码如下 ```java /** * @param g 线程组(稍后解释) * @param target 实现runnable接口的类实例 * @param name 自定义线程名 * @param stackSize 新线程所需堆栈大小,为0则忽略此参数 */ private void init(ThreadGroup g, Runnable target, String name,long stackSize) { init(g, target, name, stackSize, null, true); } ``` init方法中调用init方法 ```java /** * @param g 线程组 * @param target 实现runnable接口的类实例 * @param name 线程名 * @param stackSize * @param acc * @param inheritThreadLocals */ private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) { if (name == null) { throw new NullPointerException("name cannot be null"); } this.name = name; Thread parent = currentThread(); SecurityManager security = System.getSecurityManager(); if (g == null) { /* Determine if it's an applet or not */ /* If there is a security manager, ask the security manager what to do. */ if (security != null) { g = security.getThreadGroup(); } /* If the security doesn't have a strong opinion of the matter use the parent thread group. */ if (g == null) { g = parent.getThreadGroup(); } } /* checkAccess regardless of whether or not threadgroup is explicitly passed in. */ g.checkAccess(); /* * Do we have the required permissions? */ if (security != null) { if (isCCLOverridden(getClass())) { security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); } } g.addUnstarted(); this.group = g; this.daemon = parent.isDaemon(); this.priority = parent.getPriority(); if (security == null || isCCLOverridden(parent.getClass())) this.contextClassLoader = parent.getContextClassLoader(); else this.contextClassLoader = parent.contextClassLoader; this.inheritedAccessControlContext = acc != null ? acc : AccessController.getContext(); this.target = target; setPriority(priority); if (inheritThreadLocals && parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); /* Stash the specified stack size in case the VM cares */ this.stackSize = stackSize; /* Set thread ID */ tid = nextThreadID(); } ``` ## 实现`java.lang.Callable`接口的`run`方法 ```java public class ImplementCallable implements Callable{ public static Integer count = 0; @Override public Boolean call() throws Exception { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+" count:"+count++); } return Boolean.TRUE; } } ``` 调用 ```java public class RunThread { public static void main(String[] args) throws ExecutionException, InterruptedException { ImplementCallable callable = new ImplementCallable(); ExecutorService executorService = Executors.newFixedThreadPool(3); Future future_1 = executorService.submit(callable); Future future_2 = executorService.submit(callable); Future future_3 = executorService.submit(callable); // 结束运行 if ( future_1.get().equals(Boolean.TRUE) && future_2.get().equals(Boolean.TRUE) && future_3.get().equals(Boolean.TRUE)) { executorService.shutdown(); } } } ``` ## 线程5大状态 ```mermaid graph LR create(创建状态)--启动线程-->ready(就绪状态) block(阻塞状态)--解除阻塞-->ready ready--获得cpu资源-->run(运行状态) run--线程执行完毕或外部干涉终止线程-->death(死亡状态) run--释放cpu资源-->ready run--等待用户输入,线程休眠-->block ``` ### 手动停止线程 > 两种方式 > 1. 调用stop方法 > 2. 设置标志位 #### 调用stop方法 ```java int i = 0; while (true){ if ( ++i > 100) { Thread.currentThread().stop(); } System.out.println(this.getName()+" is running. i:"+i); } ``` #### 设置标志位 ```java boolean flag = true; int i = 0; while (flag){ if ( ++i > 100) { flag = false; } System.out.println(this.getName()+" is running. i:"+i); } ``` ### 线程礼让 `Thread.yield()` - 让当前运行在cpu上的线程暂停,由运行状态转为就绪状态 - 礼让不一定成功 ```java int i = 0; while (true){ if ( ++i > 100) { // 当循环执行100次时,礼让cpu给其他线程执行 Thread.yield(); } System.out.println(this.getName()+" is running. i:"+i); } ``` ### 线程插队 `Thread.join()` > `join` 合并线程,待此线程执行完成后,再执行其他线程,其他线程处于阻塞状态 ### 线程优先级 `Thread.setPriority(Int)` > 1-10,默认5,数字越大,优先级越高 ```java ``` ### 守护线程 `Thread.setDaemon ` > - 线程分为用户线程守护线程 > - jvm 必须确保用户线程执行完毕 > - 守护线程 等待用户线程执行完毕后 也会执行完毕 ###