线程可运行与扩展线程
threads runnable vs extends thread
我有以下代码,我正在尝试同步。
我使用了一个使用扩展线程 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();
}
}
我认为您对自己的命名约定感到困惑。我假设您正在尝试这样做:
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();
}
我有以下代码,我正在尝试同步。 我使用了一个使用扩展线程 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();
}
}
我认为您对自己的命名约定感到困惑。我假设您正在尝试这样做:
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();
}