Java的Thread类的常用方法

public class ThreadMethodDemo {     
	public static void main(String[] args) {         
		System.out.println("main 线程的id:" + Thread.currentThread().getId());         
		System.out.println("main 线程的名称:" + Thread.currentThread().getName());

	   	 MyThread3 myThread = new MyThread3();
	    	Thread thread1 = new Thread(myThread);         
		// setName() 可以设置线程名称         
		thread1.setName("线程A");         
		// 也可以通过构造器设置线程名称         
		Thread thread2 = new Thread(myThread, "线程B");
	    	// 设置线程的优先级 [1~10]         
		// 线程优化级较高的线程不一定先执行,线程的调度终还是取决于操作系统         
		thread1.setPriority(1);         
		thread2.setPriority(10);
		
	    	System.out.println("thread1 是在否活动 :" + thread1.isAlive());         
		System.out.println("thread2 是在否活动 :" + thread2.isAlive());
	
	   	 thread1.start();         
		thread2.start();         
		
		// 不能重复调用start()         
		// thread2.start();
	    	System.out.println("thread1 是在否活动 :" + thread1.isAlive());         
		System.out.println("thread2 是在否活动 :" + thread2.isAlive());

	    	// 主线程sleep 5s         
		try {             
			Thread.sleep(5000);         
			} 
		catch (InterruptedException e) {             
			// TODO Auto‐generated catch block             
			e.printStackTrace();         }
		}
		System.out.println("5 秒后....");     
	} 
}

class MyThread3 implements Runnable {
    @Override     
	public void run() {         
		// 实现Runnable接口的,无法直接使用getId(),getName()等方法         
		// 需要使用Thread.currentThread() 来获取到当前对象才行         
		System.out.println("线程的id:" + Thread.currentThread().getId());         
		System.out.println("线程的名称:" + Thread.currentThread().getName());
        for (int i = 0; i < 100; i++) {             
			System.out.println("线程的id:" + Thread.currentThread().getId() 
					+ "   线程的名称:" + Thread.currentThread().getName() 
					+ "  线程优先级:" + Thread.currentThread().getPriority());         
		}     
	} 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值