线程并发二:线程基本操作

  1. 创建线程
    常用创建线程有两种方法, 第一种发放使用匿名内部类,重载run() 方法,第二种使用Runnable接口创建线程:
//方法一
Thread t1 = new Thread(){
    @Override
    public void run(){
        System.out.prinln("hello!!");
    }
}

//方法二
public class testThread implements Runnable {

    public static void main(String[] args){
        Thread t1 = new Thread(new testThread());

        t1.start;
    }

    @Override
    public void run(){
        System.out.println("world");
    }
}

2.终止线程
Thread 提供了一个stop()方法,但是stop()方法是一个被标注为废弃的方法,Thread.stop()方法在结束线程时,会直接终止线程,并且会立即释放这个线程所持有的锁,强行把执行到一半的线程终止,可能会引起一些数据不一致的问题。

3.线程中断
线程中断是一种重要的线程协作机制,从字面上理解,中断是让目标线程停止执行,实际上并非如此,线程中断并不会使线程立即退出,而是给线程发送一个通知,告知目标线程,需要终止,至于是否终止,由目标线程自行决定。和线程中断有关的方法有三个:

public void Thread.interrupt()        //中断线程
public boolean Thread.isInterrupted()           //判断是否被中断
public static boolean Thread.interrupted()        //判断是否被中断,并清除当前中断状态

4.利用中断实现终止线程

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(){
        @Override
        public void run(){
            while(true){
                if(Thread.currentTread().isInterrupted()){
                    System.out.println("Interruted!");
                    break;
                }

                try{
                    Thread.sleep(2000);
                } catch (InterruptedException e){
                    System.out.println("Interruted when sleep!");
                    Thread.currentThread().interrupt();
                }
            }
        }
    };

    t1.start();
    Thread.sleep(1000);
    tl.interrupt();

}

5.等待(wait) 和 通知(notify)
wait() 和 notify() 的输出并不是Tread类,而是Object类, 当一个线程调用了object.wait(), 那么它就进入了object对象的等待队列。这个等待队列中,可能会有多个线程,因为系统运行中可能多个线程同时等待某一个对象。当object.notify()被调用时,它就会从这个等待队列中,随机选择一个线程,并将其唤醒。但是这个选择是不公平的,并不是先等待线程会优先被选择,这个选择完全是随机的。
除了notify()接口之外,Object对象还有一个notifyAll()方法,该方法会唤醒在这个等待队列中所有等待的线程。
无论是wait()和notify()都必须包含在对应的syncchronzied语句中,都需要首先获得目标对象的一个监视器。

public class SimpleTest(){
    final static Object object = new Object();
    public static class T1 extends Thread {
        public void run(){
            synchronized(object){
                try{
                    object.wait();
                } catch (InterruptedException e){}
            }
        }
    }

    public static class T2 extends Thread {
        public void run(){
            synchronized (object) {
                object.notify();
            }
        }

    }

    public static void main(String[] args){
        Thread t1 = new T1();
        Thread t2 = new T2();
        t1.start();
        t2.start();
    }
}

6.挂起(suspend) 和继续执行(resume)线程
Thread类的API提供了两个看起来非常有用的即可:挂起(suspend)、继续执行(resume)。但是这俩个方法不推荐使用,因为suspend()在导致线程挂起的时候,并不会释放任何资源锁,此时其他任何线程想要访问被它暂用的锁时,都会导致无法继续运行,直到对应的线程上进行了resume()操作。如果resume() 操作意外的在suspend()前执行,那么被挂起的线程可能很难有机会被继续执行。而且,对于被挂起的线程,从它线程状态上来看,还是Runnable,这严重影响我们对系统当前状态的判断。
那如果需要比较靠谱的suspend()函数该怎么办呢,我们可以用notify()和wait()方法在应用层面实现suspend()和resume(), 如下:

public class GoodSuspend {
    public static Object u = new Object();

    public static class ChangeObjectThread extends Thread {

        volatile boolean suspendme = false;

        public void suspendMe(){
            synchronized (u){
                System.out.println("wwwwwwwwwwwwwwwwwwwwwww!");
                suspendme = true;
            }
        }

        public void resumeMe(){
            suspendme = false;
            synchronized (u){
                u.notify();
            }
        }

        public void run(){
            while(true){
                synchronized (u){
                    if (suspendme) {
                        try {
                            u.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                }

                synchronized (u) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("in changeObjectThread!");
                }

                Thread.yield();
            }
        }

    }

    public static class ReadObjectThread extends Thread {

        /*public void resumeMe(){
            synchronized (u){
                System.out.println("nnnnnnnnnnnnnnnnnnnnnnnnnn!");
                u.notify();
            }
        }*/
        @Override
        public void run(){
            while (true){
                synchronized (u){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("in ReadObjectThread!");
                }

                Thread.yield();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        ChangeObjectThread t1 = new ChangeObjectThread();
        ReadObjectThread t2 = new ReadObjectThread();

        t1.start();
        t2.start();

        Thread.sleep(1000);
        t1.suspendMe();

        System.out.println("suspend t1 10 sec");

        Thread.sleep(10000);
        System.out.println("resume t1");
        t1.resumeMe();

    }

}

7.等待线程结束(join)和谦让(yield)
JDK提供了两个join()接口

public final void join() throws InterruptedException
public final synchronized void join(long millis) throws InterruptedException

第一个join()方法表示无线等待,他会一直阻塞当前线程,直到目标线程执行完毕。第二个方法给出一个最大等待时间,如果超过给定时间目标线程还在执行,当前线程将继续执行。
join()的本质是让调用线程wait()在当前线程对象实例上。

public class JoinTest {
    public volatile static int i = 0;
    public static class TestTread extends Thread {
        public void run(){
            for(i = 0; i < 100; i++);
        }
    }

    public static void main(String[] args) throws InterruptedExcepion {
        AddThread at = new AddThread();
        at.start();
        at.join();
        System.out.println(i);
    }
}

不适用join()的情况下i是一个0或者很小的数, 但加上join()之后,打印i的值永远是100.

public static native void yield();

yield() 是一个静态方法,一旦执行,它会使当前线程退让出CPU.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值