Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Direct call to a run() method

ID: java/call-to-thread-runKind: problemSecurity severity: Severity: recommendationPrecision: highTags:   - quality   - reliability   - concurrency   - external/cwe/cwe-572Query suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A direct call of aThread object’srun method does not start a separate thread. The method is executed within the current thread. This is an unusual use becauseThread.run() is normally intended to be called from within a separate thread.

Recommendation

To executeRunnable.run from within a separate thread, do one of the following:

  • Construct aThread object using theRunnable object, and callstart on theThread object.

  • Define a subclass of aThread object, and override the definition of itsrun method. Then construct an instance of this subclass and callstart on that instance directly.

Example

In the following example, the main thread,ThreadDemo, calls the child thread,NewThread, usingrun. This causes the child thread to run to completion before the rest of the main thread is executed, so that “Child thread activity” is printed before “Main thread activity”.

publicclassThreadDemo{publicstaticvoidmain(Stringargs[]){NewThreadrunnable=newNewThread();runnable.run();// Call to 'run' does not start a separate threadSystem.out.println("Main thread activity.");}}classNewThreadextendsThread{publicvoidrun(){try{Thread.sleep(10000);}catch(InterruptedExceptione){System.out.println("Child interrupted.");}System.out.println("Child thread activity.");}}

To enable the two threads to run concurrently, create the child thread and callstart, as shown below. This causes the main thread to continue while the child thread is waiting, so that “Main thread activity” is printed before “Child thread activity”.

publicclassThreadDemo{publicstaticvoidmain(Stringargs[]){NewThreadrunnable=newNewThread();runnable.start();// Call 'start' methodSystem.out.println("Main thread activity.");}}

References


[8]ページ先頭

©2009-2025 Movatter.jp