我正在开发创建线程的代码,但没有扩展线程类或实现runnable接口,即通过匿名内部类.
public class Mythread3 {
public static void main(String... a) {
Thread th = new Thread() {
public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
th.start();
Thread y = new Thread();
y.start();
}
}
Run Code Online (Sandbox Code Playgroud)
现在请告诉我,我也可以用同样的方法创建子线程.!! 我试过的是......
public class Mythread3 {
public static void main(String... a) {
Thread th = new Thread() {
public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
Thread th1 = new Thread() {
public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
th.start();
try {
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
th1.start();
}
}
Run Code Online (Sandbox Code Playgroud)
但是它有两个run()方法,我认为这不实用..请指教..!
Pet*_*rey 10
Runnable run = new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.print(i + "\n" + "..");
}
} catch (InterruptedException e) {
System.out.println(" interrupted");
}
}
};
new Thread(run).start();
new Thread(run).start();
Run Code Online (Sandbox Code Playgroud)
不要等到一个人在开始第二个之前完成,或者你有三个线程在哪一个上运行(在这种情况下,额外的线程是没有意义的)
BTW:你的synchronized没有做任何有用的事情,但它可能会导致Thread无法正常工作.