可运行线程与扩展线程

英格拉姆

我有以下代码,并且我正在尝试同步。我已经使用扩展线程t2创建了一个线程。而且我还通过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();  
}
}
shmosel

我认为您对自己的命名约定感到困惑。我认为您正在尝试这样做:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章