单例多线程测试!

package cn.vicky.sgs.service; public class ThreadTest { private Thread thread; private int temp = 0 ; public ThreadTest() { // go(); } public void go() { System.out.println("ready !"); thread = new Thread() { @Override public void run() { // synchronized (ThreadTest.this) { System.out.println(temp++); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } // } }; thread.start(); } public static void main(String[] args) { // ThreadTest t1 = new ThreadTest(); // ThreadTest t2 = new ThreadTest(); // ThreadTest t3 = new ThreadTest(); // ThreadTest t4 = new ThreadTest(); // ThreadTest t5 = new ThreadTest(); ThreadTest t = new ThreadTest(); t.go(); t.go(); t.go(); t.go(); t.go(); } }

输出:

ready !
ready !
0
ready !
1
ready !
2
ready !
3
4

// 瞬间完成

 

 

package cn.vicky.sgs.service; public class ThreadTest { private Thread thread; private int temp = 0 ; public ThreadTest() { // go(); } public void go() { System.out.println("ready !"); thread = new Thread() { @Override public void run() { synchronized (ThreadTest.this) { System.out.println(temp++); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; thread.start(); } public static void main(String[] args) { // ThreadTest t1 = new ThreadTest(); // ThreadTest t2 = new ThreadTest(); // ThreadTest t3 = new ThreadTest(); // ThreadTest t4 = new ThreadTest(); // ThreadTest t5 = new ThreadTest(); ThreadTest t = new ThreadTest(); t.go(); t.go(); t.go(); t.go(); t.go(); } }

 输出:

 

ready !
ready !
0
ready !
ready !
ready !

// 等待
1

// 等待
2

// 等待
3

// 等待
4

// 等待

 

分析:对于动态创建的Thread。无需锁住对象。

 

package cn.vicky.sgs.service; public class ThreadTest { private int temp = 0 ; private Thread thread = new Thread() { @Override public void run() { // synchronized (ThreadTest.this) { System.out.println(temp++); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } // } } }; public ThreadTest() { // go(); } public void go() { System.out.println("ready !"); thread.start(); } public static void main(String[] args) { // ThreadTest t1 = new ThreadTest(); // ThreadTest t2 = new ThreadTest(); // ThreadTest t3 = new ThreadTest(); // ThreadTest t4 = new ThreadTest(); // ThreadTest t5 = new ThreadTest(); ThreadTest t = new ThreadTest(); t.go(); t.go(); t.go(); t.go(); t.go(); } }

输出:

ready !
ready !
0
Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.start(Thread.java:595)
 at cn.vicky.sgs.service.ThreadTest.go(ThreadTest.java:27)
 at cn.vicky.sgs.service.ThreadTest.main(ThreadTest.java:39)

 

分析:一个Thread在执行时,该类中无法再次调用正在执行的Thread...需要锁住对象

 

你可能感兴趣的:(thread,多线程,exception,String,测试,Go)