2016-09-23 3 views
-6

Ich habe den folgenden Code, und ich experimentiere mit der Synchronisation. Ich habe eine Thread-Erstellung mit Extent-Thread t2 verwendet. Und ich erstelle auch einen Thread über Runnable. Allerdings kann ich nicht scheinen, dass der ausführbare Thread funktioniert.Threads runnable vs erweitert Thread

Was ist los? Ich habe Java seit gut 6 Monaten nicht geübt, um wieder in den Schwung der Dinge zu kommen.

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(); 
} 
} 
+3

Ihre Formatierung und Namenskonventionen sind schrecklich. Und dein Code kompiliert nicht. Und du benutzt deine 't1' Klasse nirgendwo. – shmosel

+1

Bitte formatieren Sie zumindest Ihren Code. Siehe [Formatieren von Code] (http://meta.stackexchange.com/a/22189/340735) –

+0

Sie sollten bessere Namenskonventionen verwenden. Außerdem gibt es einen Kompilierungsfehler bei 'Thread t1 = new Thread ((obj);'. Eine Endklammer ')' fehlt. Und was genau ist der Fehler? –

Antwort

2

Ich denke, Sie haben sich mit Ihren Namenskonventionen verwechselt. Ich nehme an, Sie haben versucht, dies zu tun:

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(); 
} 
+0

@ shmosel das hat funktioniert, aber warum muss ich eine neue Instanz von t1 mit der Tabelle obj erstellen, um den Thread zu starten? – Ingram

+0

@MrAssistance Im Gegensatz zu was zu tun? – shmosel

+0

@ Shmosel gut meine Frage ist, warum ist nicht das gleiche wie die Aufrufmethode von Thread 2. Eine Instanz von Obj wird an die Klasse MyThread2 übergeben. Es sieht so aus, dass ich in thread1 einen neuen Thread namens thread1 anlege, und dann innerhalb dieses thread1 einen neuen Thread t1 mit dem table-Objekt erzeuge. Hier werde ich verwirrt. – Ingram

Verwandte Themen