美文网首页
java创建线程(Thread)的方式

java创建线程(Thread)的方式

作者: 陈萍儿Candy | 来源:发表于2020-10-26 12:13 被阅读0次

    线程的执行:调用Thread中的start方法,java虚拟机会调用其run方法
    见Thread的start方法注释

    /**
         * Causes this thread to begin execution; the Java Virtual Machine
         * calls the <code>run</code> method of this thread.
         * <p>
         * The result is that two threads are running concurrently: the
         * current thread (which returns from the call to the
         * <code>start</code> method) and the other thread (which executes its
         * <code>run</code> method).
         * <p>
         * It is never legal to start a thread more than once.
         * In particular, a thread may not be restarted once it has completed
         * execution.
         *
         * @exception  IllegalThreadStateException  if the thread was already
         *               started.
         * @see        #run()
         * @see        #stop()
         */
        public synchronized void start() {
    

    Thread类的run方法

    /**
         * If this thread was constructed using a separate
         * <code>Runnable</code> run object, then that
         * <code>Runnable</code> object's <code>run</code> method is called;
         * otherwise, this method does nothing and returns.
         * <p>
         * Subclasses of <code>Thread</code> should override this method.
         *
         * @see     #start()
         * @see     #stop()
         * @see     #Thread(ThreadGroup, Runnable, String)
         */
        @Override
        public void run() {
            if (target != null) {
                target.run();
            }
        }
    

    创建Thread方法有两种:一从Thread类中派生的子类,使用较少
    二是从Runnable接口构造Thread类,比较常用

    1.Thread类的派生子类
    由于Thread类本身即实现了接口Runnable,只是其run方法没有任何功能,
    因此我们只需要继承Thread,重写自己的run()方法即可。

    public class Thread1 extends Thread{
    
        private Object object = new Object();
        
        @Override
        public void run() {
            super.run();
            System.out.println("thread1");
            System.out.println(this.getState());
            System.out.println(this.getThreadGroup().getName());
            Log.i("cyp", "run: "+this.getThreadGroup().activeCount());
            synchronized (object) {
                try {
    //                object.wait();
                    object.wait(10000);
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    2.提供一个Runnable对象
    由于Runnable接口只有一个方法-run(),因此继承该接口,实现run()方法,
    再将其作为参数传递给Thread的构造器即可。

    class Test1Runnable implements Runnable{
    
        private LockObject lockObject;
    
        public Test1Runnable(LockObject lockObject) {
            this.lockObject = lockObject;
        }
    
        @Override
        public void run() {
            synchronized (lockObject) {
                try {
                    Log.i("cyp", "test1Runnable:synchronized ");
                    Log.i("cyp","test1Runnable wait 方法执行前"+Thread.currentThread().getName()+",state:"+Thread.currentThread().getState());
                    lockObject.wait(10000);
                    Log.i("cyp", "test1Runnable wait 方法执行后"+Thread.currentThread().getName()+",state:"+Thread.currentThread().getState());
                    Thread.sleep(10000);
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    把Test1Runnable传入到Thread中:

    Test1Runnable runnable = new Test1Runnable(lockObject);
            one = new Thread(runnable);
            one.start();
    

    以上就是创建线程的两种方式;
    下面是对错误方式的记录:
    (1):调用Thread的run方法,应该是调用start方法,让java虚拟机去调用run方法

     Test1Runnable runnable = new Test1Runnable(lockObject);
            one = new Thread(runnable);
    //        one.start();
            // 测试run   只是调用了Test1Runnable的run方法,没有创建子线程,是在主线程main中执行
            one.run();
    

    (2):直接执行Test1Runnable的run方法,同样也是没有创建子线程,是在主线程main中执行;

    Test1Runnable runnable1 = new Test1Runnable(lockObject);
            runnable1.run();
    

    在主线程main中不要执行耗时操作

    相关文章

      网友评论

          本文标题:java创建线程(Thread)的方式

          本文链接:https://www.haomeiwen.com/subject/qwmpmktx.html