Java多线程的理解

一、创建线程

  Thread thread = new myThread();

    //myThread继承Thread方法,然后重写run方法

二、搞明白 wait(),notify(),notifyAll 

  1.这些方法都是针对对象使用的,通常和同步锁一起使用(synchronized),

      synchronized(object){

          object.wait();

        }

  2.wait()使此对象释放资源,让出cpu,线程进入等待队列

  3.notify 是唤醒等待此对象资源的线程,并继续执行同步块,直至结束,一般唤醒都写在同步块的最后

  4.notifyAll 唤醒所有等待此资源的线程

三、代码实例

  

package com.test.thread;

public class mythread extends Thread{

private String name;
private Object prev;
private Object self;

public mythread(String name,Object prev,Object self) {
// TODO Auto-generated constructor stub
this.name=name;
this.prev=prev;
this.self=self;
}
@Override
public void run() {
int count = 10,i=0;
while(count > 0){
synchronized(prev){
synchronized(self){
System.out.println(count--);
self.notify();
}
try{
prev.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
synchronized(self){
self.notify();
}
//super.run();
}

}

 

 

package com.test.thread;

public class myMain {

public static void main(String[] args) throws Exception{

Object a = new Object();
Object b = new Object();
Object c = new Object();

mythread pa = new mythread("A", c, a);
mythread pb = new mythread("B", a, b);
mythread pc = new mythread("C", b, c);

new Thread(pa).start();
new Thread(pb).start();
new Thread(pc).start();


}
}

posted @ 2017-04-10 10:53  ThrownBug  阅读(194)  评论(0编辑  收藏  举报