多线程实例代码

时间:2022-02-01 18:18:58
class MyThread implements Runnable{// 实现Runnable接口
public void run(){// 覆写run()方法
for(int i=0;i<3;i++){
System.out.println(Thread.currentThread().getName()
+ "运行,i = " + i) ;// 取得当前线程的名字
}
}
};
public class CurrentThreadDemo{
public static void main(String args[]){
MyThread mt = new MyThread() ;// 实例化Runnable子类对象
new Thread(mt,"线程").start() ;// 启动线程
mt.run() ;// 直接调用run()方法
}
};

输出结果1:

main运行,i = 0
main运行,i = 1
main运行,i = 2
线程运行,i = 0
线程运行,i = 1
线程运行,i = 2

输出结果2:

main运行,i = 0
线程运行,i = 0
线程运行,i = 1
线程运行,i = 2
main运行,i = 1
main运行,i = 2