public abstract class Multithread implements Runnable{
static Thread t1 = new Thread(){
public synchronized void run(){
try {
for(;;){
System.out.println("java");
t1.sleep(300);
}
} catch (Exception e) {
System.out.println("Exception"+e);
}
}
};
static Thread t2 = new Thread(){
public synchronized void run(){
try{
for(;;){
System.out.println("world");
t2.sleep(300);
}
}catch(Exception e){
System.out.println("Exception"+e);
}
}
};
public static void main(String[] args) {
try{
t1.start();
t2.start();
}catch(Exception e){
System.out.println("Exception "+e);
}
}
@Override
public void run() {
System.out.println("running");
}
}
例外 O/P:
java
world
java
world
java
world
.
.
.
.
观察到 我尝试对线程使用 sleep() ,它们在某个时间点像这样重叠 -
java
java
world
java
world
world
java
..
预计 我需要这两个线程并行运行,并且它不应该重叠,任何一个线程都可以启动。任何想法?