zoukankan      html  css  js  c++  java
  • Thread部分总结以及小例子

    Thread总结:一直以来用thread比较多,一般会在同步以及ui中用到.以下对于经常用作为简单介绍.

    一 实现方法:

    一种直接new thread,另外一种是实现Runnable接口,在创建thread的时候将Runnable直接丢进去即可.另外从java的唯一继承性那么用runnable更适合.

    Example:

    public class MainActivity extends Activity {
        Thread thread1;
        Thread thread2;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            operateThread();
            thread1.start();
            thread2.start();
        }


        public void operateThread(){
            Log.d("ThreadTest", "threadGroup");
            thread1 = new Thread(new Runnable(){
                public void run(){
                    while(true){
                        Log.d("ThreadTest","thread_1.running: ");
                        try {
                            Thread.sleep(4000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
            
            class MyRunnable implements Runnable {
                public void run(){
                    while(true){
                        Log.d("ThreadTest","thread_2.running: ");
                        //Thread.yield();
                        try {
                            Thread.sleep(4000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
            thread2 = new Thread(new MyRunnable());
        };

    运行结果:
    04-25 15:05:38.299 28518 28518 D ThreadTest: threadGroup
    04-25 15:05:38.301 28518 28536 D ThreadTest: thread_1.running:
    04-25 15:05:38.319 28518 28537 D ThreadTest: thread_2.running:
    04-25 15:05:42.302 28518 28536 D ThreadTest: thread_1.running:
    04-25 15:05:42.323 28518 28537 D ThreadTest: thread_2.running:


    二.方法解说:
      run()-->线程运行时所执行的代码
       start()-->用于启动线程
       sleep(long millis)-->线程休眠,交出CPU,让CPU去执行其他的任务,然后线程进入阻塞状态,sleep方法不会释放锁
      yield()-->使当前线程交出CPU,让CPU去执行其他的任务,但不会进入阻塞状态,而是重置为就绪状态,yield方法不会释放锁.和sleep区别是sleep会阻塞会再执行,yield让出cpu后,和其它线程存在竞争状态.
      join()-->当前主线程等待其他线程执行完毕后,再来继续执行Thread.join()后面的代码
      interrupt()//中断线程,自stop函数过时之后,我们通过interrupt方法和isInterrupted()方法来停止正在运行的线程,注意只能中断已经处于阻塞的线程
       getId()-->当前线程id
       getName()/setName()-->获取和设置线程的名字
       getPriority()/setPriority()-->获取和设置线程的优先级,property用1-10整数表示,默认优先级是5,优先级最高是10,优先级高的线程被执行的机率高
      setDaemon()/isDaemo()//设置和判断是否是守护线程
      currentThread()-->静态函数获取当前线程
      wait()/notyfy/notifyAll-->他们是属于Obeject对象,不是属于线程。它们用在线程同步时synchronized语句块中。wait交出cpu,让CPU去执行其他的任务,线程进入阻塞状态,同时也会释放锁.notify()并不会让当前线程休眠,但会唤醒休眠的线程。 (notifyAll方法就会通知所有等待这个对象控制权的线程继续运行)
        eg:wait():我等会儿再用这把锁,CPU也让给你们,我先休息一会儿!notify()意思是说,我用完了,你们谁用?

     关于wait && notify的简单例子如下:
    public class MainActivity extends Activity {
        Thread thread1;
        Thread thread2;
        boolean threadRunning;
        final Object object = new Object();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            operateThread();

        public void operateThread(){
            Log.d("ThreadTest", "threadGroup");
            thread1 = new Thread(new Runnable(){
                public void run(){
                    synchronized (object) {
                       threadRunning = true;
                       for(int i =0;i <= 100;i++){
                           Log.d("ThreadTest","thread_1.running: i: " + i);
                           if(i== 50){
                               try {
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                           }
                       }
                       threadRunning = false;
                    }
                }
            });
            thread1.start();
            
            class MyRunnable implements Runnable {
                public void run(){
                 synchronized (object) {
                    for(int i=0;i<100;i++){
                        Log.d("ThreadTest","thread_2.running: i: " + i);
                        if(i== 50){
                            object.notify();
                        }
                    }
                  }
                }
            }
            thread2 = new Thread(new MyRunnable());
            thread2.start();
    04-26 10:33:32.376  4956  4956 D ThreadTest: threadGroup
    04-26 10:33:32.379  4956  4976 D ThreadTest: thread_1.running: i: 0
          ......中间thread_1一直在运行,由于有object的占用
    04-26 10:33:32.381  4956  4976 D ThreadTest: thread_1.running: i: 49
    04-26 10:33:32.381  4956  4976 D ThreadTest: thread_1.running: i: 50//到50就释放锁,让出cpu,进入wait阻塞状态
    04-26 10:33:32.381  4956  4977 D ThreadTest: thread_2.running: i: 0
          ........thread_2获取锁后运行,
    04-26 10:33:32.382  4956  4977 D ThreadTest: thread_2.running: i: 50
          ........thread_2在50的时候notify持有object对象的线程后,不释放锁,以及不会让出cpu
    04-26 10:33:32.382  4956  4977 D ThreadTest: thread_2.running: i: 51
    04-26 10:33:32.383  4956  4977 D ThreadTest: thread_2.running: i: 99
          .......线程2执行完后线程1运行
    04-26 10:33:32.384  4956  4976 D ThreadTest: thread_1.running: i: 51
    04-26 10:33:32.384  4956  4976 D ThreadTest: thread_1.running: i: 52

      Thread线程主要状态
    (1) New  实例化tread后就是new状态
    (2) Runnable 调用start后处于runnable
    (3) Running 调用start后切被cpu执行
     (4)  Blocked 调用join()、sleep()、wait()使线程处于Blocked状态
     (5)  Dead    线程的run()方法运行完毕或被中断或被异常退出,线程将会到达Dead状态

    对于这些thread介绍如有不清楚或者不对的地方,望指出,大家可以共同进步.以及有兴趣的地方大家可以一起讨论.

  • 相关阅读:
    close 不弹出对话框
    ASP.NET会话(Session)保存模式
    ASP.NET页面刷新后滚动条保留在刷新前的位置 MaintainScrollPositionOnPostback
    CSS实现垂直居中的5种方法
    ExpandStackTrace
    HttpTunnel
    PropertyAccess类 Linq.Expressions 实现
    DatagramResolver
    AsyncUdpClient 类
    C# LockFreeStack类
  • 原文地址:https://www.cnblogs.com/syyh2006/p/8950512.html
Copyright © 2011-2022 走看看