From the course: Advanced Java Programming
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
The Runnable interface in Java - Java Tutorial
From the course: Advanced Java Programming
The Runnable interface in Java
- A second way to handle threads in Java is the runnable interface. in this example, I have a class called runnable example, which implements runnable. One of the benefits of impelmenting a runnable interface, instead of extending the thread class, is that if my class extends the thread class, than I can't extend any other classes. In Java, you are only allowed to extend one class. But because my class implements runnable, it can extend other classes if I want it to. I have then overridden the run method and in here I have put all the codes that I want to run when I create a thread using my runnable. In this example, I have used a while loop to print out every number from 1 to 100, and after each number it prints the name of the current thread. I also have a main class with a main method in it. In order to use my runnable example class, the first thing I need to do is create a variable of type thread. I will call it thread1 and assign it to a new thread. There is a constructor of the…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.