public static void main(String[] args) { new MyThread().start(); } static class MyThread extends Thread{ @Override public void run() { System.out.println("extend MyThread"); } }
new Thread(new ThreadFormRunnable()).start(); static class ThreadFormRunnable implements Runnable{ @Override public void run() { System.out.println("from Runnable Thread"); } }
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; } }
/** /*Thread state for a thread which has not yet started. */ NEW
/** /* 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,
对于操作系统的线程状态:可能运行态,也可能就绪态。
/** /* 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 */
也就是争取对象锁的线程的状态,争取失败的会进入我们常说的"锁池"。
/** /* 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. */
主动调用进入等待池,停下当前线程。
与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: */
/** /* Thread state for a terminated thread. /* The thread has completed execution. */
线程进入WAITING状态,只有被唤醒或者被中断。wait方法会释放对象的锁
ObjectA.notify,唤醒一个ObjectA对象监视器上的随机一个线程。
被唤醒的线程将以常规方式与在ObjectA对象上主动同步的所有线程进行竞争。幼儿园化就是,首先得知道一个事实notify()和wait()方法需要获取对象锁,不然语法报错。也就是拿到synchronized的那个锁。那被唤醒后的线程B就开始正常执行,明显调用ObjectA.notify的线程也是synchronized的,明显B得先拿到这个synchronized的锁才能继续走。
进入TIMED_WAITING状态,不会释放当前对象的锁。
让出CPU,加入同级优先队列的末尾
中断线程,然而并不会直接改变线程的状态,设置一个中断标志位。
在ThreadA调用ThreadB.join();
thread,A等待B线程终止,也就是合并线程B进入A中。