Java 里的创建线程

1. 实现Runnable 接口

        创建线程的最简单的方法就是创建一个实现Runnable 接口的类,一个类仅需实现一个run()的简单方法。

public class ThreadRunnaber implements Runnable{
			
			Thread t;
			
			ThreadRunnaber(){
				t = new Thread(this,"DemoChild");
				System.out.println("Child Thread Run"+t);
				t.start();
			}
	
			public void run() {
				try {
					 for(int i=5;i>0;i--) {
						System.out.println("Child Thread: " + i);  
						Thread.sleep(500);
					 }				
					
				} catch (InterruptedException e) {
					System.out.println("Child Thread inerrupted");					
				}
				 System.out.println("Exiting child thread."); 
			}

		public static void main(String[] args) {

			new ThreadRunnaber();//创建一个子线程
			
			 try {
				 for(int i = 5; i > 0; i--) {
					 System.out.println("Main Thread: " + i); 
					 Thread.sleep(1000); 
				 } 
			 } catch(InterruptedException e ) {
				 System.out.println("Main thread interrupted."); 
			 }
			 System.out.println("Main thread exiting."); 
		}
}

2.可以继承Thread类。

public class ThreadExtends extends Thread{//继承Thread类
			
			 ThreadExtends(){	
				 super("Demo MyThread");
				 System.out.println(this);
				 start();
			}
			 
		public void run(){
			for (int i=5;i>0;i--) {
				try {
					System.out.println("Child Thread GO "+ i);
					Thread.sleep(500);			
				}catch(InterruptedException e){
					System.out.println("Child Thrad interrupted");
				}								
			}
			System.out.println("Child Thrad Over");
		} 	 
		public static void main(String[] agrs) {
			new ThreadExtends();
			
			for (int i=5;i>0;i--) {
				try {
					System.out.println("Main Thread GO "+i);
					Thread.sleep(1000);			
				}catch(InterruptedException e){
					System.out.println("Main Thrad interrupted");
				}								
			}System.out.println("Main Thrad Over");
			
		}

}

3.多开线程 及判断线程存活 等待子线程结束

public static void main(String[] args) {
			ThreadRunnaber tr1=	new ThreadRunnaber("one");
			ThreadRunnaber tr2=	new ThreadRunnaber("two");
			ThreadRunnaber tr3=	new ThreadRunnaber("three");//创建多线程
			
			  if (tr1.t.isAlive())System.out.println(tr1 +"  still live");//线程还在执行
			  if (tr2.t.isAlive())System.out.println(tr2 +"  still live");
			  if (tr3.t.isAlive())System.out.println(tr3 +"  still live");
			
			 try {
				System.out.println("---------------Waiting for child finish -------------------------"); 
				tr1.t.join();
				tr2.t.join();
				tr3.t.join();	//等待子线程结束			
			 } catch(InterruptedException e ) {
				 System.out.println("Main thread interrupted."); 
			 }
			 if ((!tr1.t.isAlive()) && (!tr2.t.isAlive()) &&  (!tr3.t.isAlive())){
				 
				 System.out.println("Main thread exiting.");  //线程结束
			 }
			 
		}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值