Java多线程相关知识整理分享。1)wait() notify() sleep()sleep是Thread类的函数,wait和notify是Object的函数。sleep的时候keep对象锁,wait的时候release 对象锁。sleep时监控状态依然保持。wait进入等待池,只有针对该对象发出了notify才会进入对象锁池。Sleep时间过了就会恢复运行,wait后等到notify了,也不一定是立即运行。Wait和notify是非static函数,sleep是Thread类的static函数。 2)stop() destroy() suspend()都是Thread类的函数,都不推荐使用。stop放弃了所有的lock,会使得对象处于一种不连贯状态。destroy的时候如果还keep了某些资源的lock,那就死定了suspend会继续持有所有的lock,容易发生死锁。 3)创建线程:继承Thread类,override它的abstract函数run实现Runnable接口,写run函数。 4)让线程跑起来:start()函数 5)例子:四个线程,两个inc,两个dec,没有顺序:public class ThreadTest { private int j; public static void main(String[] args) { ThreadTest tt=new ThreadTest(); Inc inc= tt.new Inc(); Dec dec= tt.new Dec(); for(int i=0;i<2;i++){ Thread t=new Thread(inc); t.start(); t=new Thread(dec); t.start(); } } private synchronized void inc(){ j++; System.out.println(Thread.currentThread().getName()+"-inc:"+j); } private synchronized void dec(){ j--; System.out.println(Thread.currentThread().getName()+"-dec:"+j); } class Inc implements Runnable{ public void run() { for(int i=0;i<100;i++){ inc(); } } } class Dec implements Runnable{ public void run() { for(int i=0;i<100;i++){ dec(); } } }}本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134413.htm