Download Article
Download Article
This wikiHow will teach you how to run multiple threads in Java. You'll want to run multiple threads to create a program that processes multiple actions at once; the more CPU your computer has, the more processes it can run concurrently.
Steps
-
Enter the following code:
public void run ( )
- This code provides a beginning point for your multiple threads to run.
-
Enter the following code:
Thread ( Runnable threadObj , String threadName );
- '
threadObj
' is the class that starts the runnable thread and 'threadName
' is the name of the thread.
Advertisement - '
-
Enter the following code:
void start ();
- Use this code after you've fleshed out a thread object and this code will start it.
- Your finished code could look like this
class RunnableDemo implements Runnable { private Thread t ; private String threadName ; RunnableDemo ( String name ) { threadName = name ; System . out . println ( "Creating " + threadName ); } public void run () { System . out . println ( "Running " + threadName ); try { for ( int i = 4 ; i > 0 ; i --) { System . out . println ( "Thread: " + threadName + ", " + i ); // Let the thread sleep for a while. Thread . sleep ( 50 ); } } catch ( InterruptedException e ) { System . out . println ( "Thread " + threadName + " interrupted." ); } System . out . println ( "Thread " + threadName + " exiting." ); } public void start () { System . out . println ( "Starting " + threadName ); if ( t == null ) { t = new Thread ( this , threadName ); t . start (); } } } public class TestThread { public static void main ( String args []) { RunnableDemo R1 = new RunnableDemo ( "Thread-1" ); R1 . start (); RunnableDemo R2 = new RunnableDemo ( "Thread-2" ); R2 . start (); } }
-
Execute your code. If you used the coding from the example, the output should read
Creating Thread - 1 Starting Thread - 1 Creating Thread - 2 Starting Thread - 2 Running Thread - 1 Thread: Thread - 1 , 4 Running Thread - 2 Thread: Thread - 2 , 4 Thread: Thread - 1 , 3 Thread: Thread - 2 , 3 Thread: Thread - 1 , 2 Thread: Thread - 2 , 2 Thread: Thread - 1 , 1 Thread: Thread - 2 , 1 Thread Thread - 1 exiting . Thread Thread - 2 exiting .
Advertisement
Expert Q&A
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Tips
Submit a Tip
All tip submissions are carefully reviewed before being published
Name
Please provide your name and last initial
Thanks for submitting a tip for review!
About This Article
Article Summary
X
1. Enter public void run ( )
into your code.
2. Use Thread(runnable threadObj, String threadName);
in your code.
3. Enter void start ();
in your code.
4. Execute your code.
Did this summary help you?
Thanks to all authors for creating a page that has been read 16,890 times.
Advertisement