Wellcom to my Blog for Javascript

java 多线程中的wait方法的详解

java多线程中的实现方式存在两种:

方式一:使用继承方式

例如:

 1 PersonTest extends Thread{
 2 
 3 String name;
 4 
 5 public PersonTest(String name){
 6 
 7 super(name);
 8 
 9 this.name=name
10 
11 }
12 
13 }

 

 

方式二:使用实现接口的方式

例如:

 1 public PersonT implements Runnable{
 2 public void run(){
 3 //此处为执行的代码
 4 }
 5 }
 6 //实例化方式
 7 public jacktest{
 8 public static void main(String[] args){
 9 PersonT t=new PersonT();
10 Thread tt=new Thread(t,"线程1");
11 tt.start();
12 }
13 }

 

wait使用方式:

package TestThread.ThreadSynchronized.TestInterruptedException;

public class InterruptDemo {
    public static void main(String[] args) {
        TestWait t = new TestWait("线程1");
        TestWait t1 = new TestWait("线程2");
        t.start();
        t1.start();
    }
}

class TestWait extends Thread {
    String name;

    public TestWait(String name) {
        super(name);
        this.name = name;
    }

    public synchronized void run() {
        for (int i = 0; i < 5; i++) {
            if (i == 4) {
                try {
                    // 等待之后立即释放当前锁,并且进入等待池中等待唤醒
                    // 当等待池中的线程被唤醒后,再次执行此语句之后的语句
                    this.wait();
                    System.out.println(Thread.currentThread().getName() + ":我还没有被执行到!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":当前的值为--->" + i);
        }
    }
}

 

posted on 2017-03-24 09:20  温柔的鲨鱼  阅读(8625)  评论(1编辑  收藏  举报

导航