转载

Thread常用知识

一、创建线程的方法

1.1继承Thread类

public static void main(String[] args) {  
  new MyThread().start();  
}  
static class MyThread extends Thread{  
  @Override  
  public void run() {  
  System.out.println("extend MyThread");  
    }  
}

1.2实现Runnable方法

new Thread(new ThreadFormRunnable()).start();
static class ThreadFormRunnable implements Runnable{  
  @Override  
  public void run() {  
  System.out.println("from Runnable Thread");  
    }  
}

1.3ExecutorService、Callable<Class>、Future

1.4线程池

ExecutorService pool= Executors.newFixedThreadPool(10);  
List<Future> list=new ArrayList<Future>();  
for (int i = 0; i < 10; i++) {  
        Callable callable=new MyCallable(i);  
        Future future=pool.submit(callable);  
        list.add(future);  
    }  
  pool.shutdown();  
  list.forEach((x)->{  
  try {  
        System.out.println(x.get().toString());  
  } catch (InterruptedException e) {  
        e.printStackTrace();  
  } catch (ExecutionException e) {  
        e.printStackTrace();  
  }  
 });  
}  
  
static class MyCallable implements Callable{  
    private int number;  
    public MyCallable(int source) {  
        number=source;  
    }  
  
  @Override  
  public Object call() throws Exception {  
       return number*number;  
  }  
}

二、线程的六个状态

1、NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED

NEW

/**
/*Thread state for a thread which has not yet started.
 */
NEW

RUNNABLE

/**  
/* Thread state for a runnable thread.  A thread in the runnable 
/* state is executing in the Java virtual machine but it may 
/* be waiting for other resources from the operating system 
/* such as processor. 
 */
RUNNABLE,

对于操作系统的线程状态:可能运行态,也可能就绪态。

BLOCKED

/**  
/* Thread state for a thread blocked waiting for a monitor lock. 
/* A thread in the blocked state is waiting for a monitor lock 
/* to enter a synchronized block/method or 
/* reenter a synchronized block/method after calling
 */

也就是争取对象锁的线程的状态,争取失败的会进入我们常说的"锁池"。

WAITING

/**  
/* Thread state for a waiting thread. 
/* A thread in the waiting state is waiting for another thread to  
/* perform a particular action.  

/* For example, a thread that has called <tt>Object.wait()
/* on an object is waiting for another thread to call  
/* <tt>Object.notify()</tt> or <tt>Object.notifyAll() on
/* that object. A thread that has called <tt>Thread.join() 
/* is waiting for a specified thread to terminate.  
 */

主动调用进入等待池,停下当前线程。

TIMED_WAITING

与WAITING就多了个超时的机制。

/**  
 /* Thread state for a waiting thread with a specified waiting time. 
 /* A thread is in the timed waiting state due to calling one of 
 /* the following methods with a specified positive waiting time:
 */

TERMINATED

/**  
 /* Thread state for a terminated thread. 
 /* The thread has completed execution. 
 */

2、线程状态间转换关系

Thread常用知识

三、线程的常用方法

wait

线程进入WAITING状态,只有被唤醒或者被中断。wait方法会释放对象的锁

notify

ObjectA.notify,唤醒一个ObjectA对象监视器上的随机一个线程。

被唤醒的线程将以常规方式与在ObjectA对象上主动同步的所有线程进行竞争。幼儿园化就是,首先得知道一个事实notify()和wait()方法需要获取对象锁,不然语法报错。也就是拿到synchronized的那个锁。那被唤醒后的线程B就开始正常执行,明显调用ObjectA.notify的线程也是synchronized的,明显B得先拿到这个synchronized的锁才能继续走。

sleep

进入TIMED_WAITING状态,不会释放当前对象的锁。

yield

让出CPU,加入同级优先队列的末尾

interrupt

中断线程,然而并不会直接改变线程的状态,设置一个中断标志位。

1、Running不会终止,仅仅修改中断标志位

2、sleep调用使线程进入TIMED_WAITING状态,调用interrupt方法,会throw InterruptException.

join

在ThreadA调用ThreadB.join();

thread,A等待B线程终止,也就是合并线程B进入A中。

原文  https://segmentfault.com/a/1190000021576075
正文到此结束
Loading...