代码如下:
class TestThreadMethod extends Thread {
#
# public static int shareVar = 0;
#
# public TestThreadMethod(String name) {
#
# super(name);
#
# }
#
# public synchronized void run() {
#
# for (int i = 0; i < 3; i++) {
#
# System.out.print(Thread.currentThread().getName());
#
# System.out.println(" : " + i);
#
# try {
#
# Thread.sleep(100);// (4)
#
# } catch (InterruptedException e) {
#
# System.out.println("Interrupted");
#
# }
#
# }
#
# }
#
# }
#
# public class MyTest {
#
# public static void main(String[] args) {
#
# TestThreadMethod t1 = new TestThreadMethod("t1");
#
# TestThreadMethod t2 = new TestThreadMethod("t2");
#
# t1.start(); // (1)
#
# t1.start(); // (2)
#
# // new Thread(t1).start();// (4)
#
# // new Thread(t1).start();// (5)
#
# // new Thread(t2).start(); (3)
#
# }
#
# } 为什么运行两个t1.start();就会报错,Exception in thread "main" java.lang.IllegalThreadStateException
如果运行两个new Thread(t1).start();就没有问题了呢?
class TestThreadMethod extends Thread {
#
# public static int shareVar = 0;
#
# public TestThreadMethod(String name) {
#
# super(name);
#
# }
#
# public synchronized void run() {
#
# for (int i = 0; i < 3; i++) {
#
# System.out.print(Thread.currentThread().getName());
#
# System.out.println(" : " + i);
#
# try {
#
# Thread.sleep(100);// (4)
#
# } catch (InterruptedException e) {
#
# System.out.println("Interrupted");
#
# }
#
# }
#
# }
#
# }
#
# public class MyTest {
#
# public static void main(String[] args) {
#
# TestThreadMethod t1 = new TestThreadMethod("t1");
#
# TestThreadMethod t2 = new TestThreadMethod("t2");
#
# t1.start(); // (1)
#
# t1.start(); // (2)
#
# // new Thread(t1).start();// (4)
#
# // new Thread(t1).start();// (5)
#
# // new Thread(t2).start(); (3)
#
# }
#
# } 为什么运行两个t1.start();就会报错,Exception in thread "main" java.lang.IllegalThreadStateException
如果运行两个new Thread(t1).start();就没有问题了呢?
解决方案 »
- HTTP Status 500 - Dispatch[/monitor] to method totalSheetMonitor returned an exc
- 傻傻的问一句什么eclipse插件能根据库表结构生成pojo和hibernate映射文件
- hibernate使用jndi数据源取不到数据
- 谁实际使用过teamsite,请联系我,有酬咨询
- Widget 开发团队邀请您以来开发
- Oracle和DB2的最大区别是什么啊
- The value for the useBean class attribute ToFromExcel is invalid.
- 100分请教如何设置JTABLE的表头高度?
- hibernate的find方法问题
- 菜鸟提问:SHP to WKT 谁有这样的经验吗,求分享求帮助
- 求教,java采集集城中商品信息
- struts2 页面用一个list迭代出来的内容中有textfield 提交到另一个action时,如何得到录入的内容?
如果运行两个new Thread(t1).start();就没有问题了呢,因为产生两个对象。
t1.start();
这是同一个线程启动两次,必报异常new Thread(t1)产生了一个新的线程对象,它不同于t1。
new 两次产生两个不同的线程对象,调用它们的start当然没有问题
t1.start();
t1.start();必报异常new Thread(t1)产生了一个新的线程对象。所以可以
你都把 run 给 synchronized 了,还怎么多线程啊。
就你找个例子如果想看 synchronized 的效果,你只能通过 new Thread(t1).start();
new Thread(t1).start();去启动两个线程,但是这样的话,你的 t1 不需要从 Thread 继承,实现 Runnable 接口就行了。
你如果想在 t1 上通过调用两次 start() 去启动两个线程是不可能的。一个线程只能被启动一次,启动后在调用 start 的话就会抛异常的。看看 JDK API 文档你就知道了。