Java 多线程Part5_1模仿多线程

package ken.part5;

public class Part5 {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread myThread = new MyThread();
		myThread.run();
		while(true){
			System.out.println("Main方法在执行");	
		}
	}
}
 class MyThread{	
		public void run() {
			while(true){
				System.out.println("MyThread类的run方法在执行");
				}			
		}		
}

这里是模仿多线程写了两个类,main函数所在的类创建另一个MyTread类对象,调用其run方法,但是这里任然只有一个线程,就是主线程main。所以程序一直输出的就是调用MyThread对象的run()方法。

开创线程有两种方法一种是继承Thread类,覆写run()方法。另一种是实现Runnable接口实现run()方法。

第一种  继承类

package ken.part5;

public class Part5_2 {	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread02 myThread = new MyThread02();
		myThread.start();
		while(true){
			System.out.println("main() 方法在运行");
		}
	}
}
class MyThread02 extends Thread{
	public void run() {
		while(true){
			System.out.println("MyThread方法");
		}
	}
}

第二种:实现接口

package ken.part5;

public class Part5_3 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread03 myThread03 = new MyThread03();
		Thread thread = new Thread(myThread03);
		thread.start();
		while(true){
			System.out.println("main方法");	
		}
	}
}
class MyThread03 implements Runnable{
	public void run() {
	while(true){
		System.out.println("mythread方法");
	}		
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值