报错:java.lang.IllegalThreadStateException

一、问题代码:

1、继承Thread类

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread th1 = new Thread() {
			public void run() {
				System.out.println("我结束了!");
			}
		};
		th1.start();
		while(th1.isAlive()) {}
		th1.start();
	}
}

结果:

2、实现Runnable接口

public class T1 {
	public static void main(String agrs[]) {
		Thread zhangsan, lisi;
		Bathroom room = new Bathroom();
		zhangsan = new Thread(room);
		lisi = new Thread(room);
		zhangsan.setName("张三");
		lisi.setName("李四");
		lisi.start();
		zhangsan.start();
		while(zhangsan.isAlive()) {}
		zhangsan.start();
	}
}

class Bathroom implements Runnable {
	int water = 500;

	@Override
	public  void run() {
		if (Thread.currentThread().getName() == "张三") {
			while (water > 0) {
				System.out.println("张三洗澡喽");
				water -= 50;
			}
		}
		else if (Thread.currentThread().getName() == "李四") {
			while (water > 0) {
				System.out.println("李四洗澡啦");
				water -= 40;
			}
		} 
	}
}

结果:(同样报错)

报错:java.lang.IllegalThreadStateException_第1张图片        可以推得一个线程对象不能被启动两次。

 二、解决办法(以第一种情况为例,第二种同理)

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread th1 = new Thread() {
			public void run() {
				System.out.println("我结束了!");
			}
		};
		th1.start();
		while(th1.isAlive()) {}
		th1 = new Thread() {
			public void run() {
				System.out.println("我又结束了!");
			}
		};
		th1.start();
	}

结果:

 运行正常。

三、结论

同一个线程对象不能被启动两次,若想启动两次需要重新new一个对象。

 

你可能感兴趣的:(java,开发语言)