目次
スレッドの構築
スレッドの説明
必要な情報
新しく構築された Thread オブジェクト (new Thread()) は親スレッド (現在のスレッド) によって領域が割り当てられ、子スレッドは親の
Threadの継承
コード
命令
Threadソースコードの発見(スレッドはRunnableを実装)により、スレッドが実際にはスレッドのインスタンスを表すRunnableインターフェースを実装するインスタンスであることがわかりました。 、そして、
Callable インターフェイスと Future を使用して、返された結果でマルチスレッドを実装します
Callable インターフェイスと Future インターフェイスを使用してスレッドを作成します。具体的には、Callableインターフェースの実装クラスを作成し、clam()メソッドを実装します。そして、FutureTask クラスを使用して Callable 実装クラスのオブジェクトをラップし、この FutureTask オブジェクトを Thread オブジェクトのターゲットとして使用してスレッドを作成します。
参考代码
启动线程的注意事项
Thread与Runnable的关系
实现关系
区别
ホームページ Java &#&チュートリアル Java 同時実行スレッドの使用と起動スレッドの構築

Java 同時実行スレッドの使用と起動スレッドの構築

Sep 30, 2017 am 10:38 AM
java 使用


スレッドの構築

スレッドの説明

  • スレッドは、プログラム内の実行スレッドです。Java 仮想マシンを使用すると、アプリケーションは複数のスレッドを同時に実行できます。

  • 各スレッドには優先順位があり、優先順位の高いスレッドの実行が優先順位の低いスレッドより優先されます。各スレッドはデーモンとしてマークされる場合とマークされない場合があります。スレッド内で実行されているコードが新しい Thread オブジェクトを作成すると、新しいスレッドの初期優先順位は作成スレッドの優先順位に設定され、作成スレッドがデーモン スレッドである場合に限り、新しいスレッドはデーモンになります。

  • Java 仮想マシンが起動すると、通常は 1 つの非デーモン スレッドが存在します (通常、指定されたクラスの main メソッドを呼び出します)。 Java 仮想マシンは、次のいずれかの状況が発生するまでスレッドを実行し続けます:
    1. Runtime クラスの exit メソッドが呼び出され、セキュリティ マネージャーによって終了操作の実行が許可されます。
    2. run メソッドの呼び出しから戻るか、run メソッドの外に伝播する例外をスローすることによって、デーモン スレッドではないすべてのスレッドが実行を停止しました。

  • スレッドの実装方法は後続の章で紹介します

ソースコードリファレンスは次のとおりです:

/**
 * A <i>thread</i> is a thread of execution in a program. The Java
 * Virtual Machine allows an application to have multiple threads of
 * execution running concurrently.
 * <p>
 * Every thread has a priority. Threads with higher priority are
 * executed in preference to threads with lower priority. Each thread
 * may or may not also be marked as a daemon. When code running in
 * some thread creates a new <code>Thread</code> object, the new
 * thread has its priority initially set equal to the priority of the
 * creating thread, and is a daemon thread if and only if the
 * creating thread is a daemon.
 * <p>
 * When a Java Virtual Machine starts up, there is usually a single
 * non-daemon thread (which typically calls the method named
 * <code>main</code> of some designated class). The Java Virtual
 * Machine continues to execute threads until either of the following
 * occurs:
 * <ul>
 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
 *     called and the security manager has permitted the exit operation
 *     to take place.
 * <li>All threads that are not daemon threads have died, either by
 *     returning from the call to the <code>run</code> method or by
 *     throwing an exception that propagates beyond the <code>run</code>
 *     method.
 * </ul>
 * <p>
 * There are two ways to create a new thread of execution. One is to
 * declare a class to be a subclass of <code>Thread</code>. This
 * subclass should override the <code>run</code> method of class
 * <code>Thread</code>. An instance of the subclass can then be
 * allocated and started. For example, a thread that computes primes
 * larger than a stated value could be written as follows:
 * <hr><blockquote><pre class="brush:php;toolbar:false">
 *     class PrimeThread extends Thread {
 *         long minPrime;
 *         PrimeThread(long minPrime) {
 *             this.minPrime = minPrime;
 *         }
 *
 *         public void run() {
 *             // compute primes larger than minPrime
 *              . . .
 *         }
 *     }
 * 
ログイン後にコピー

*

* The following code would then create a thread and start it running: *

 *     PrimeThread p = new PrimeThread(143);
 *     p.start();
 * 
ログイン後にコピー
*

* The other way to create a thread is to declare a class that * implements the Runnable interface. That class then * implements the run method. An instance of the class can * then be allocated, passed as an argument when creating * Thread, and started. The same example in this other * style looks like the following: *


 *     class PrimeRun implements Runnable {
 *         long minPrime;
 *         PrimeRun(long minPrime) {
 *             this.minPrime = minPrime;
 *         }
 *
 *         public void run() {
 *             // compute primes larger than minPrime
 *              . . .
 *         }
 *     }
 * 
ログイン後にコピー

*

* The following code would then create a thread and start it running: *

 *     PrimeRun p = new PrimeRun(143);
 *     new Thread(p).start();
 * 
ログイン後にコピー
*

* Every thread has a name for identification purposes. More than * one thread may have the same name. If a name is not specified when * a thread is created, a new name is generated for it. *

* Unless otherwise noted, passing a {@code null} argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * @author unascribed * @see Runnable * @see Runtime#exit(int) * @see #run() * @see #stop() * @since JDK1.0 */ publicclass Thread implements Runnable {

必要な情報

スレッドを実行する前に、最初にスレッドオブジェクトを構築する必要があります。構築時に必須です。スレッドが属するスレッド グループ、スレッドの優先順位、デーモン スレッドかどうかなど、スレッドに必要な属性を指定します。新しい Thread では、次のメソッドが呼び出され、Thread オブジェクトがインスタンス化されます。 初期化コードは以下の通りです:

    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     */
    private void init(ThreadGroup g, Runnable target, String name,                      
    long stackSize, AccessControlContext acc) {        
    if (name == null) {            
    throw new NullPointerException("name cannot be null");
        }        
        this.name = name;        //当前线程作为该线程的父线程
        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();        //线程组的获取:如果传入的参数为空首先获取系统默认的安全组,如果为空获取父线程的安全组
        if (g == null) {            
        /* Determine if it&#39;s an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }            /* If the security doesn&#39;t have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();        /*
         * Do we have the required permissions?
         */
        if (security != null) {            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();        
        this.group = g;        //设置daemon 、priority 属性为父线程对应的值
        this.daemon = parent.isDaemon();        
        this.priority = parent.getPriority();        
        
        if (security == null || isCCLOverridden(parent.getClass()))            
        this.contextClassLoader = parent.getContextClassLoader();        
        else
            this.contextClassLoader = parent.contextClassLoader;        
            this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();        
                this.target = target;
        setPriority(priority);        //将父线程的InheritableThreadLocal复制过来
        if (parent.inheritableThreadLocals != null)            
        this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);        
                /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;        /* Set thread ID */ 
        //生成线程id(一个long型的字段threadSeqNumber)
        tid = nextThreadID();
    }
ログイン後にコピー

結論

新しく構築された Thread オブジェクト (new Thread()) は親スレッド (現在のスレッド) によって領域が割り当てられ、子スレッドは親の

Daemon と優先順位を継承します。 thread そして、リソースをロードする contextClassLoader と継承可能な ThreadLocal も、子スレッドにスレッド ID を割り当てます

。実行可能なスレッド オブジェクトは初期化作業を完了し、ヒープ メモリ内で実行を待機しています。 ビルド方法

Threadの継承

コード

//方法1通过继承Thread实现class MyThread extends Thread{

    //需要实现的方法,该方法执行具体的业务逻辑
    @Override    public void run() {
        System.out.println(Thread.currentThread().getName()
                +" @@@@ MyThread。run()我是通过继承Thread实现的多线程");
    }

}
ログイン後にコピー

命令

Threadソースコードの発見(スレッドはRunnableを実装)により、スレッドが実際にはスレッドのインスタンスを表すRunnableインターフェースを実装するインスタンスであることがわかりました。 、そして、

スレッドを開始する唯一の方法は、Thread クラスの start() インスタンス メソッドを使用することです

。 start() メソッドは、新しいスレッドを開始して run() メソッドを実行するネイティブ メソッドです。この方法でマルチスレッドを実装するのは非常に簡単です。独自のクラスを通じて Thread を直接拡張し、run() メソッドをオーバーライドすることで、新しいスレッドを開始し、独自に定義した run() メソッドを実行できます。 run() メソッドのメソッド本体は、スレッドが完了する必要があるタスクを表し、

スレッド実行本体

と呼ばれます。このスレッド クラス オブジェクトが作成されると、新しいスレッドが作成され、スレッド新規状態になります。スレッドオブジェクトが参照するstart()メソッドを呼び出すことで、スレッドは実行可能状態になります。このとき、CPUのスケジューリングタイミングによっては、すぐにスレッドが実行されない場合があります。 インターフェイス Runnable を実装します

コード

//方法2通过实现runnable接口
//实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,
//并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。class MyRunnable implements Runnable{

    @Override    public void run() {
        System.out.println(Thread.currentThread().getName()+                
        " @@@@ MyRunnable。run()我是通过实现Runnable接口实现的多线程");
    }

}
ログイン後にコピー

Callable インターフェイスと Future を使用して、返された結果でマルチスレッドを実装します

Callable インターフェイスと Future インターフェイスを使用してスレッドを作成します。具体的には、Callableインターフェースの実装クラスを作成し、clam()メソッドを実装します。そして、FutureTask クラスを使用して Callable 実装クラスのオブジェクトをラップし、この FutureTask オブジェクトを Thread オブジェクトのターゲットとして使用してスレッドを作成します。

値を返すことができるタスクは Callable インターフェイスを実装する必要があります。同様に、戻り値のないタスクは Runnable インターフェイスを実装する必要があります。 Callable タスクを実行した後、Future オブジェクトを取得できます。オブジェクトに対して get を呼び出して、Callable タスクによって返されるオブジェクトを取得します。スレッド プール インターフェイス ExecutorService と組み合わせると、返される結果で伝説的なマルチスレッドを実現できます。 Executor の使用方法については、以降の記事で詳しく紹介します)。


//方法3通过Executor框架实现class MyCallable implements Callable<Integer>{
    //需要实现call方法而不是run方法
    @Override    public Integer call() throws Exception {        return 100;
    }
}
ログイン後にコピー
スレッドを開始します

ソースコード分析によると:

1. オブジェクトの初期化が完了した後、start メソッドを実行することでスレッドが実行され、Java 仮想マシンはスレッドの run メソッドを呼び出します。スレッドのビジネス ロジックを実行します。
  • 2. start メソッドを呼び出した後、同時に実行されている 2 つのスレッドがあることがわかります。現在のスレッド (親スレッドは、Java 仮想マシンに同期的に通知します)スレッド プランナーがアイドル状態であるため、start メソッドを呼び出すスレッドはすぐに開始される必要があります]、呼び出しから start メソッドに返されます) と別のスレッド (run メソッドを実行します)。
  • 3. スレッドを複数回開始することは違法です。特に、スレッドの実行が終了した場合、再起動することはできません。
  • 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() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group&#39;s list of threads
         * and the group&#39;s unstarted count can be decremented. */
        group.add(this);        boolean started = false;        try {
            start0();
            started = true;
        } finally {            try {                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();
ログイン後にコピー

参考代码

public class TestCreateThread {    public static void main(String[] args) {
        Thread myThread = new MyThread();
        myThread.setName("myThread");
        myThread.start();

        Runnable myRunnable = new MyRunnable();
        Thread myRunnableThread = new Thread(myRunnable);
        myRunnableThread.setName("myRunnableThread");
        myRunnableThread.start();

        Thread myRunnableThread2 = new MyThread(myRunnable);
        myRunnableThread2.setName("myRunnableThread2");
        myRunnableThread2.start();        //执行结果参考如下:
        //myThread @@@@ MyThread。run()我是通过继承Thread实现的多线程
        //myRunnableThread2 @@@@ MyThread。run()我是通过继承Thread实现的多线程
        //myRunnableThread @@@@ MyRunnable。run()我是通过实现Runnable接口实现的多线程

        //测试callable方法
        // 创建MyCallable对象
        Callable<Integer> myCallable = new MyCallable();    
        //使用FutureTask来包装MyCallable对象
        FutureTask<Integer> ft = new FutureTask<Integer>(myCallable); 
        //FutureTask对象作为Thread对象的target创建新的线程
        Thread thread = new Thread(ft);
        thread.start();//启用

        //获取信息
        try {            //取得新创建的新线程中的call()方法返回的结果
            //当子线程此方法还未执行完毕,ft.get()方法会一直阻塞,
            //直到call()方法执行完毕才能取到返回值。
            int sum = ft.get();
            System.out.println("sum = " + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }        //使用ExecutorService处理多线程
        ExecutorService pool = Executors.newFixedThreadPool(10);  
        Future<Integer> f = pool.submit(myCallable);  
        // 关闭线程池  
        pool.shutdown(); 
        try {            int sum1 = f.get();
            System.out.println("sum1 = " + sum1);
        } catch (InterruptedException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
ログイン後にコピー

启动线程的注意事项


Java 同時実行スレッドの使用と起動スレッドの構築


无论何种方式,启动一个线程,就要给它一个名字!这对排错诊断系统监控有帮助。否则诊断问题时,无法直观知道某个线程的用途。

Thread与Runnable的关系

实现关系

Thread实现接口Runnable,并且实现了run方法,代码参考如下:

        //如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;
        //否则,该方法不执行任何操作并返回。
        //Thread 的子类应该重写该方法。
        /**
         * If this thread was constructed using a separate
         * <code>Runnable</code> run object, then that
         * <code>Runnable</code> object&#39;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类中的run()方法时,会首先判断target是否存在,存在则执行target中的run()方法,也就是实现了Runnable接口并重写了run()方法的类中的run()方法。当时如果该Runnable的子类是通过一个继承Thread的子类(该且重写了run方法),则真正执行的是Thread子类重写的run方法(由于多态的原因)。

以上がJava 同時実行スレッドの使用と起動スレッドの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Javaの平方根 Javaの平方根 Aug 30, 2024 pm 04:26 PM

Java の平方根のガイド。ここでは、Java で平方根がどのように機能するかを、例とそのコード実装をそれぞれ示して説明します。

Javaの完全数 Javaの完全数 Aug 30, 2024 pm 04:28 PM

Java における完全数のガイド。ここでは、定義、Java で完全数を確認する方法、コード実装の例について説明します。

Javaのアームストロング数 Javaのアームストロング数 Aug 30, 2024 pm 04:26 PM

Java のアームストロング番号に関するガイド。ここでは、Java でのアームストロング数の概要とコードの一部について説明します。

Java の乱数ジェネレーター Java の乱数ジェネレーター Aug 30, 2024 pm 04:27 PM

Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

ジャワのウェカ ジャワのウェカ Aug 30, 2024 pm 04:28 PM

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

Javaのスミス番号 Javaのスミス番号 Aug 30, 2024 pm 04:28 PM

Java のスミス番号のガイド。ここでは定義、Java でスミス番号を確認する方法について説明します。コード実装の例。

Java Springのインタビューの質問 Java Springのインタビューの質問 Aug 30, 2024 pm 04:29 PM

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8 Stream Foreachから休憩または戻ってきますか? Java 8 Stream Foreachから休憩または戻ってきますか? Feb 07, 2025 pm 12:09 PM

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

See all articles