Java多线程的常用方法

1. 获取线程的名字:

  • String name = currentThread.getName();

2. 设置线程的名字:

  • currentThread.setName(“t1”);

3. 获取当前线程:

  • Thread currentThread = Thread.currentThread();

4. 唤醒线程

  • t.interrupt();
package Demo;

public class ThreadMethod {

	public static void main(String[] args) {

		
		ThreadM t = new ThreadM();
		Thread t1 = new Thread(t);
		
		
		//设置t1线程的名字
		t1.setName("t1");
		
		//开启t1线程
		t1.start();
		
		//当前线程
		Thread currentThread = Thread.currentThread();
		//设置当前线程名字
		currentThread.setName("main");
		
		//当前线程的名字
		String name = currentThread.getName();
		
		for (int i = 0; i < 100; i++) {
			System.out.println(name + "--->" + i);
		}
		
	}
	
}


class ThreadM implements Runnable{

	@Override
	public void run() {
		
		//当前线程
		Thread currentThread = Thread.currentThread();
		
		//当前线程的名字
		String name = currentThread.getName();
		
		for (int i = 0; i < 100; i++) {
			System.out.println(name + "--->" + i);
		}
		
	}
	
}
唤醒线程

package Demo;

public class WakeUp {

	public static void main(String[] args) {
		//创建线程对象
		Thread t = new Thread(new Wake());
		
		t.setName("t");
		
		//开启线程
		t.start();
		
		//休眠5秒后唤醒t线程
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*唤醒t线程(这种方式是依赖Java的异常机制,使Thread.sleep(1000*60*24*365)
		  发生java.lang.InterruptedException异常,catch捕捉后再执行下面的方法,打断休眠)*/
		t.interrupt();
		
	}
	
}

class Wake implements Runnable{

	@Override
	public void run() {
		
		System.out.println(Thread.currentThread().getName() + " -> begain");
		//休眠一年
		try {
			Thread.sleep(1000*60*24*365);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " -> end");
	}
}


5. 终止线程

package Demo;

public class StopThread {

	public static void main(String[] args) throws InterruptedException {
		
		StopTest s = new StopTest();
		//创建线程对象
		Thread t = new Thread(s);
		
		t.setName("t");
		
		//开启线程
		t.start();
		
		//5秒后终止线程t
		Thread.sleep(5000);
		
		//几乎不用,会丢失数据
		//t.stop();
		
		//终止线程
		s.run = false;
		
	}
	
}

class StopTest implements Runnable{

	//标识,当run为false终止线程
	boolean run = true;
	
	public void run() {
		
		//当run为false终止线程
		for (int i = 0; i < 100; i++) {
			if (run) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "--->" + i);
			}else {
				return;
			}
		}
		
		

	}
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值