-5

I have the following code, and i am experimenting with synchronization. I have used one thread creation using extend thread t2. And I am also creating one thread via runnable. However i cant seem to get the runnable thread working.

What is wrong? I havent practiced java for a good 6 months so getting back into the swing of things.

package threadingchapter4;

class Table {
void printTable(int n) {
synchronized (this) {// synchronized block
for (int i = 1; i <= 5; i++)
{
System.out.println(n * i + " "+ Thread.currentThread().getName() + " ("
+ Thread.currentThread().getId());
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
                }
}
}// end of the method
}

class t1 implements Runnable {
Table t;

t1(Table t) {
this.t = t;
}

public void run() {
t.printTable(5);
}

}

class MyThread2 extends Thread {
Table t;

MyThread2(Table t) {
this.t = t;
}

public void run() {
t.printTable(100);
}
}
public class TestSynchronizedBlock1 {
public static void main(String args[]){  
Table obj = new Table();//only one object  
Thread t1 = new Thread(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();
t2.start();  
}
}
Ingram
  • 654
  • 2
  • 7
  • 29

1 Answers1

2

I think you've confused yourself with your naming conventions. I assume you were trying to do this:

public static void main(String args[]){  
    Table obj = new Table();//only one object  
    Thread thread1 = new Thread(new t1(obj));  // t1 is the Runnable class
    MyThread2 thread2 = new MyThread2(obj);  
    thread1.start();
    thread2.start();  
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • @ shmosel thats worked, but why do i have to create a new instance of t1 with the Table obj to start the thread? – Ingram Sep 23 '16 at 22:19
  • @MrAssistance As opposed to doing what? – shmosel Sep 23 '16 at 22:24
  • @ shmosel well my question is why is not the same as the call method of thread 2. An instance of obj is passed to class MyThread2. It looks like that in thread1 I create a new Thread called thread1, and then within that i create a new thread t1 with the table object. This is where i am getting confused. – Ingram Sep 23 '16 at 22:31
  • @MrAssistance A `Runnable` is not the same as a `Thread`, but it can be passed to a `Thread` for similar effect. See [this question](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread) for more details. – shmosel Sep 23 '16 at 22:35
  • @ shmosel http://stackoverflow.com/a/30192904/3786491 thats what i needed – Ingram Sep 23 '16 at 22:52