publicenumState{/** * 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 * {@link Object#wait() Object.wait}. */BLOCKED,/** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>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()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * 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: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */TIMED_WAITING,/** * Thread state for a terminated thread. * The thread has completed execution. */TERMINATED;}
publicclassTestVolatile{staticvolatileboolean flag =false;publicstaticvoidmain(String[] args){newThread(()->{try{Thread.sleep(2000);}catch(InterruptedException e){ e.printStackTrace();} flag =true;System.out.println("子线程修改flag的值为: "+ flag);}).start();// while(true) 调用底层代码,效率极高,不会从主存中再次获取被其他线程修改过的数据while(true){if(flag){System.out.println("flag is true 主线程结束循环!");break;}}}}
classMyThreadextendsThread{publicMyThread(String name){super(name);}@Overridepublicvoidrun(){System.out.println("Thread is running.");System.out.println(Thread.currentThread().getName());}}MyThread thread =newMyThread("t1");thread.start();
classMyThreadextendsThread{@Overridepublicvoidrun(){System.out.println("Thread is running.");System.out.println(Thread.currentThread().getName());}}MyThread thread =newMyThread();thread.setName("t1");thread.start();
通过匿名内部类写法
newThread("t1"){@Overridepublicvoidrun(){System.out.println("Thread is running.");System.out.println(Thread.currentThread().getName());}}.start();
publicsynchronizedvoidstart(){/** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */if(threadStatus !=0)thrownewIllegalThreadStateException();/* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this);boolean started =false;try{start0(); started =true;}finally{try{if(!started){ group.threadStartFailed(this);}}catch(Throwable ignore){/* do nothing. If start0 threw a Throwable then it will be passed up the call stack */}}}privatenativevoidstart0();
synchronized (lock) { while (条件不满足) { lock.wait(); } //继续执行后面操作}
例1:如果使用if,wait中的线程被唤醒时,不会再次判断if中的条件
publicclassSimpleWakeupDemo{privatevolatilestaticboolean flag =true;privatestaticfinalObject lock =newObject();publicstaticbooleancondition(){System.out.println(Thread.currentThread().getName()+"判断flag = "+ flag);return flag;}publicstaticvoidmain(String[] args){Thread t1 =newThread(){@Overridepublicvoidrun(){synchronized(lock){if(condition()){try{System.out.println(Thread.currentThread().getName()+" before wait"); lock.wait();System.out.println(Thread.currentThread().getName()+" after wait");}catch(InterruptedException e){thrownewRuntimeException(e);}}System.out.println(Thread.currentThread().getName()+"打印flag = "+ flag);}}};Thread t2 =newThread(){@Overridepublicvoidrun(){synchronized(lock){try{Thread.sleep(900); lock.notifyAll();}catch(InterruptedException e){thrownewRuntimeException(e);}}}}; t1.start(); t2.start();}}
Thread-0判断flag = trueThread-0 before waitThread-0 after waitThread-0打印flag = true
如果改成while,可以看到wait结束后,会再次判断条件是否成立
while(condition()){try{System.out.println(Thread.currentThread().getName()+" before wait"); lock.wait();System.out.println(Thread.currentThread().getName()+" after wait");}catch(InterruptedException e){thrownewRuntimeException(e);}}
Thread-0判断flag = trueThread-0 before waitThread-0 after waitThread-0判断flag = trueThread-0 before wait
publicclassTestThread{publicstaticvoidmain(String[] args){for(int i =0; i <10; i++){newMyThread("T"+i).start();}}}classMyThreadextendsThread{privatestaticInteger i =1000;//同步监视器,锁privatestaticObject object =newObject();publicMyThread(String name){super(name);}@Overridepublicvoidrun(){while(true){synchronized(object){if(i >0){ i--;System.out.println(Thread.currentThread().getName()+"->"+ i);}else{break;}}}}}
3.3 Runnable创建线程时,使用同步方法加锁
publicclassTestRunnable{publicstaticvoidmain(String[] args){Runnable runnable =newRunnable(){privateint num =1000;@Overridepublicvoidrun(){while(true){this.show();}}publicsynchronizedvoidshow(){try{Thread.sleep(20);}catch(InterruptedException e){ e.printStackTrace();}if(num >0){ num--;System.out.println(Thread.currentThread().getName()+"->"+ num);}}};for(int i =0; i <10; i++){newThread(runnable,"T"+ i).start();}}}
3.4 Thread创建线程时,使用同步方法加锁
publicclassTestThread{publicstaticvoidmain(String[] args){TicketTest ticketTest =newTicketTest();for(int i =0; i <10; i++){newThread("T"+i){@Overridepublicvoidrun(){while(true){ ticketTest.test();}}}.start();}}staticclassTicketTest{privateint num =1000;privatesynchronizedvoidtest(){if(num >0){ num--;System.out.println(Thread.currentThread().getName()+"->"+ num);}}}}