Java多线程编程#执行线程示例

说明:main代表一个线程,这个是主线程;而继承自Thread或实现Runable接口的类叫做线程类,线程类内部的run方法是用户要执行的任务,叫做线程体。线程体需要开发者自己实现。
package com.boonya.base;
/*主线程*/
public class MultipleThread { 
	
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		System.out.println("我是主线程");
		ThreadUseExtendsThread thread1=new ThreadUseExtendsThread();     //第1个线程
		Thread thread2=new Thread(new ThreadUseRunable(), "thread2");      //第2个线程
		thread1.start();
		thread1.setPriority(6);       //设置线程一的优先级为6
		try {
			 System.out.println("主线程挂起5秒.......");
			 Thread.sleep(5000);       //主线程将挂起5秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	    System.out.println("重回主线程");
	    if(thread1.isAlive()){
	    	thread1.stop();
	    	System.out.println("thread1休眠时间过长,主线程杀死thread1");
	    }else{
	    	 System.out.println("主线程没有发现thread1,thread1已经顺利执行完毕");
	         thread2.start();                //启动线程2
	    }
	    try {
	    	 System.out.println("主线程挂起3秒......");
			Thread.sleep(3000);       //主线程将挂起3秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	    System.out.println("重回主线程");
	    
	    if(thread2.isAlive()){
	    	thread2.stop();
	    	System.out.println("thread2休眠时间过长,主线程杀死thread2");
	    }else{
	        System.out.println("主线程没有发现thread2,thread2已经顺利执行完毕");
	        System.out.println("主线程结束");
	    }
		
	}

}

/*执行线程体:---《方式1》-------*/
class  ThreadUseExtendsThread extends Thread{
	
	public ThreadUseExtendsThread(){}

	@Override
	public void run() {
		System.out.println("---------我是Thread的子类线程实例-------------");
		System.out.println("我将挂起5秒");
		System.out.println("回到主线程,请稍等,刚才主线程挂起可能还没有醒来");
		try {
			 System.out.println("挂起5秒......");
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


/*执行线程体:---《方式2》-------*/
class  ThreadUseRunable  implements Runnable{
	
   public ThreadUseRunable(){}
   
	@Override
	public void run() {
		System.out.println("---------我是Thread类线程实例的实现了Runable接口-------------");
		System.out.println("我将挂起1秒");
		System.out.println("回到主线程,请稍等,刚才主线程挂起可能还没有醒来");
		try {
			System.out.println("挂起1秒.......");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

你可能感兴趣的:(java,thread)