Java Thread

创建: 2020/12/11

完成: 2020/12/11

 java.lang.Thread

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

创建
直接重载Thread类
new Thread() {
    @Override
    public void run() {
        ...
    }
}

 

 
构造函数里给Runnable
  • 先实现Runnable再传递
    class RunnableDummy implements Runnable {
        public void run() {
            ...
        }
    }
    Thread t = new Thread(new RunnableDummy());
  • 用匿名类
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            ...
        }
    });

     

  • 直接作为lamda函数传递
    Thread t = new Thread(() -> {...});

     

 

静态常量
MAX_PRIORITY  
NORM_PRIORITY  
MIN_PRIORITY  
构造函数  
Thread()  
Thread(Runnable target)  
Thread(Runnable target, String name)  
Thread(String name)  
Thread(ThreadGroup, group, Runnable target)  
Thread(ThreadGroup group, Runnable target, String name)  
Thread(ThreadGroup group, RUnnable target, String name, long stackSize)  
Thread(ThreadGroup group, String name)  

 

静态方法

 

static Thread currentThread()  
static void sleep(long msec) throws InterruptedException  
static void sleep(long msec, int nsec) throws InterruptedException  
static void yield() 把CPU使用权让给其他线程
static boolean holdsLock(Object obj)  
static boolean interrupted()  

 

实例方法

 

属性
long getId()  
String getName()

获取Thread名称

  • 生成时没给name的为thread-数字
int getPriority()  
Thread.State getState()

返回状态

Thread.State

NEW 没启动
RUNNABLE 运行中
BLOCKED

?

A thread that is blocked waiting for a monitor lock is in this state.

WAITING 等候其他thread
TIMED_WAITING 待机中(sleep)
TERMINATED 结束

 

ThreadGroup getThreadGroup() 获取所属的thread group
   
   
   
   
   
   
设置

 

void setDaemon(boolean b)  
void setName(String name)  
void setPriority(int p)  
   

 

判断
boolean isAlive()

除去NEW和TERMINATED外的状态都是alive

(呼出start起到结束进程为止)

boolean isDaemon()

是否是守护进程

boolean isInterrupted()  
   
   
void interrupt()  

join

在进程结束前停止主进程

void join() throws InterruptedException

 
void join(long msec) throws InterruptedException 至多等待参数时间
void join(long msec, int nsec) throws InterruptedException 同上

 

void run() thread的具体操作, 被@Override
void start()  
String toString()  
   
   
   
   
   
   

 

多线程下的同步
方法前加上  synchronized  

静态方法锁类,实例方法锁实例

  • 即同步下面obj里的方法
  • 同时只准一个线程去运行方法
synchronized代码块
synchronized (obj) {
    ...
}
  •  同上可以是实例对象也可以是类
线程间的通讯

Object的实例方法

void wait() throws InterruptedException

void wait(long msec) throws InterruptedException

void wait(long msec, int nsec) throws InterruptedException

 
void notify()

呼出notify()/notifyAll()仅通知其他thread,不会关锁

(运行出synchronized代码块或方法才会解锁)

void notifyAll()  
   
更好的通讯

java.utli.concurrent

posted @ 2020-12-11 09:42  懒虫哥哥  阅读(225)  评论(0编辑  收藏  举报