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();
}
}
Ihre Formatierung und Namenskonventionen sind schrecklich. Und dein Code kompiliert nicht. Und du benutzt deine 't1' Klasse nirgendwo. – shmosel
Bitte formatieren Sie zumindest Ihren Code. Siehe [Formatieren von Code] (http://meta.stackexchange.com/a/22189/340735) –
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? –