问题发现
先看一段代码:
public class ThreadLocalTest {
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
Thread thread1 = new Thread(()->synchronizedTest.sync1());
System.out.println("thread1-define");
Thread thread2 = new Thread(()->synchronizedTest.sync2());
System.out.println("thread2-define");
thread1.run();
System.out.println("thread1-run");
thread2.run();
System.out.println("thread2-run");
}
}
public class SynchronizedTest {
public void sync1() {
while (true) {
}
}
public void sync2() {
System.out.println("HAHA");
}
}
执行结果:
thread1-define
thread2-define
然后进程就死循环了
问题分析
java中thread的start()和run()的区别:
-
start() 方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。
-
run() 方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码。
Thread的源码如下:
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
所以直接调用run方法并没有启动线程!
所以直接调用run方法并没有启动线程!
所以直接调用run方法并没有启动线程!
解决方案
改成如下代码:
public class ThreadLocalTest {
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
Thread thread1 = new Thread(()->synchronizedTest.sync1());
System.out.println("thread1-define");
Thread thread2 = new Thread(()->synchronizedTest.sync2());
System.out.println("thread2-define");
thread1.start();
System.out.println("thread1-run");
thread2.start();
System.out.println("thread2-run");
}
}
public class SynchronizedTest {
public void sync1() {
while (true) {
}
}
public void sync2() {
System.out.println("HAHA");
}
}
线程就能正常启动了,执行结果如下:
thread1-define
thread2-define
thread1-run
thread2-run
HAHA
网友评论