我有以下代码,我正在尝试同步。 我使用扩展线程t2创建了一个线程创建。我也通过runnable创建一个线程。但是我似乎无法让runnable线程正常工作。
有什么问题?我已经练习了6个月的Java,所以重新开始了。
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();
}
}
答案 0 :(得分:2)
我认为你已经对自己的命名惯例感到困惑。我假设你试图这样做:
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();
}