Java 线程的几个方法

一. join( )方法的讲解。
join( )函数的作用是:该线程死了后,才能执行下个线程,说白了,就是使异步线程变成同步的。文字有点抽象,我们一起来看个例子:

final Thread thread2 = new Thread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            for (int i = 0; i < 5; i++) {
                System.out.println("============" + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    });

    Thread thread = new Thread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub

            try {

                System.out.println(thread2.getName());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    thread2.start();
    try {
        thread2.join();

        thread.start();
        //thread.join();

        System.out.println("newSingleThreadExecutor。。。。。");

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

输出结果说明:

============0
============1
============2
============3
============4
newSingleThreadExecutor。。。。。
Thread-0

从结果上不难看出,线程thread2 跑完后,才执行下面的操作,这里注意一点就是没想到主线程也被阻塞了。什么原因呢?原来是这样的:

join方法实现是通过wait(小提示:Object 提供的方法)。 当main线程调用t.join时候,main线程会获得线程对象t的锁(wait 意味着拿到该对象的锁),调用该对象的wait(等待时间),直到该对象唤醒main线程 。

二.wait()函数

由于 wait() 与 notify/notifyAll() 是放在同步代码块中的,因此线程在执行它们时,即该线程肯定是获得了锁。当线程执行wait()时,会把当前的锁释放,然后让出CPU,进入等待状态。 当执行notify/notifyAll方法时,会唤醒一个处于等待该 对象锁 的线程,然后继续往下执行,直到执行完退出对象锁锁住的区域(synchronized修饰的代码块)后再释放锁。看完理论,我们来看看代码:

public class main {
private final Object object = new Object();
private Lock lock = new ReentrantLock();

/**
 * @param args
 */
public static void main(String[] args) {
    Vector obj = new Vector();
    Thread consumer = new Thread(new Consumer(obj));
    Thread producter = new Thread(new Producter(obj));
    consumer.start();
    producter.start();
}

}

/* 消费者 */

class Consumer implements Runnable {
private Vector obj;

public Consumer(Vector v) {
    this.obj = v;
}

public void run() {
    synchronized (obj) {
        while (true) {
            try {
                if (obj.size() == 0) {
                    obj.wait();
                }
                System.out.println("Consumer:goods have been taken");
                System.out.println("obj size: " + obj.size());
                obj.clear();
                obj.notify();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

}

/* 生产者 */

class Producter implements Runnable {
private Vector obj;

    public Producter(Vector v) {
        this.obj = v;
    }

    public void run() {
        synchronized (obj) {
            while (true) {
                try {
                    if (obj.size() != 0) {
                        obj.wait();
                    }

                    System.out.println("Producter:obj are ready");
                    obj.add(new String("apples"));
                    obj.notify();

                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

测试结果:

Producter:obj are ready
Consumer:goods have been taken
obj size: 1
Producter:obj are ready
Consumer:goods have been taken
obj size: 1
Producter:obj are ready
Consumer:goods have been taken
obj size: 1

三 .yield()函数

先检测当前是否有相同优先级的线程处于同可运行状态,如有,则把 CPU 的占有权交给此线程,否则继续运行原来的线程。所以yield()方法称为“退让”,它把运行机会让给了同等优先级的其他线程。 sleep方法允许较低优先级的线程获得运行机会,但yield()方法执行时,当前线程仍处在可运行状态,所以不可能让出较低优先级的线程些时获得CPU占有权

四.sleep()方法

这个方法比较简单,我在这里就不过解释啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值