多线程——实现Runnable接口实现一个多线程

实现Runnable接口实现一个多线程

Runnable接口源码:

package java.lang;
//Runnable接口源码只有一个run方法
public interface Runnable {
public abstract void run();
}

实现Runnable的两个多线程类:

public class RunnableThread1 implements Runnable {

    @Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":线程启动....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class RunnableThread2 implements Runnable { @Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":线程启动....");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

测试:

public class TestThread {
public static void main(String[] args) {
RunnableThread1 thread1 = new RunnableThread1();
RunnableThread2 thread2 = new RunnableThread2(); Thread t1 = new Thread(thread1, "线程1");
Thread t2 = new Thread(thread2);// 线程2为系统命名 // 不能再此处调用sleep()方法 t1.start();
t2.start();
}
}
结果:
Thread-0:线程启动....
线程1:线程启动....
线程1:线程启动....
Thread-0:线程启动....
线程1:线程启动....
线程1:线程启动....
Thread-0:线程启动....
线程1:线程启动....
Thread-0:线程启动....
Thread-0:线程启动....
上一篇:java.lang.Comparable 接口 详解


下一篇:azkaban使用--依赖dependencies作业