// t1.start() 永远使用 start --》 start0 (本地方法) 去启动线程 而非 调用 run 方法 // 这里记得 t1.join() 是等待t1线程执行完成才会继续往下执行 // t1.setdaemon(true) 设置为守护线程,也就是不那么重要的,jvm 在所有非守护线程执行完成后就会退出,垃圾回收就是一个守护线程 // 虽然我们以后使用 concurrent 包来进行并发,但是基础原理一定要掌握牢固 // 进程 六种状态 new | running | blocking | waiting | timed waiting|terminiated thread 常用方法 构造方法 thread(runnable target,string name) 静态方法: thread.currentthread().getname() thread.sleep(1000) // java 中 单位是毫秒 所以 1000ms = 1 s,python 中直接是 秒
public class counter { private int value; public synchronized void inc(int m){ this.value+=m; } public synchronized void dec(int m){ this.value-=m; } }
package com.ghc.test; import java.util.concurrent.locks.lock; import java.util.concurrent.locks.reentrantlock; public class counter { private lock lock = new reentrantlock(); private int value; public void inc(int m){ if(lock.trylock()){ try{ this.value+=m; }finally{ lock.unlock(); } } } public void dec(int m){ if(lock.trylock()){ try{ this.value-=m; }finally { lock.unlock(); } } } public int getvalue(){ lock.lock(); try{ return this.value; }finally { lock.unlock(); } } public static void main(string [] args) throws interruptedexception{ system.out.println(thread.currentthread().getname()+" start..."); new thread(()->{ system.out.println(thread.currentthread().getname()+" start..."); try{ thread.sleep(1000); }catch (interruptedexception e){} system.out.println(thread.currentthread().getname()+" end..."); },"download thread").start(); thread.sleep(500); system.out.println(thread.currentthread().getname()+" end..."); } }
package com.ghc.test; import java.util.concurrent.locks.reentrantreadwritelock; public class counter { private final reentrantreadwritelock lock = new reentrantreadwritelock(); private final reentrantreadwritelock.readlock readlock = lock.readlock(); private final reentrantreadwritelock.writelock writelock = lock.writelock(); private int value; public void inc(int m){ // 写 锁 writelock.lock(); try{ this.value+=m; }finally { writelock.unlock(); } } public void dec(int m){ // 读锁 readlock.lock(); try{ this.value-=m; }finally { readlock.unlock(); } } }
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论