This article is not about to talk the difference between implement Runnable interface and extends Thread class, but to talk about Object sharing in two ways while creating Threads.
package com.concurrency.util;
public class RunnableImpl implements Runnable {
private int id = 0;
@Override
public void run() {
System.out.println("I'm, " + this.id + ", waitting for the lock...");
synchronized(this){
System.out.println("Runnable..." + this.id++);
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
/**
* @param args
*/
public static void main(String[] args) {
//below codes sharing one Object for three Threads.
RunnableImpl run = new RunnableImpl();
Thread th1 = new Thread(run); // here use Thread constructor - Thread(Runnable run)
th1.start();
Thread th2 = new Thread(run);
th2.start();
Thread th3 = new Thread(run);
th3.start();
//below codes is the same like using extends Thread, every Thread owns its one pure Object.
RunnableImpl run1 = new RunnableImpl();
Thread th4 = new Thread(run1); // here use Thread constructor - Thread()
th4.start();
RunnableImpl run2 = new RunnableImpl();
Thread th5 = new Thread(run2); // here use Thread constructor - Thread()
th5.start();
RunnableImpl run3 = new RunnableImpl();
Thread th6 = new Thread(run3); // here use Thread constructor - Thread()
th6.start();
}
}
Testing result: