public class TT implements Runnable{
int b=100;
public synchronized void m1()throws Exception {
b=1000;
Thread.sleep(5000);
}
public void m2(){
System.out.println(b);
}
public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws InterruptedException{
TT t1=new TT();
Thread t2=new Thread();
t2.start();
t1.m2();
}
} 这是马士兵讲的线程同步面试题 ,视频上结果是b=1000 而我运行却是b=100 我晕 这是为什么啊线程sleep后 处于什么状态啊! 假设sleep后线程是等待状态,那么加了 synchronized 后,此线程依旧不释放资源,就应该是b=100啊
int b=100;
public synchronized void m1()throws Exception {
b=1000;
Thread.sleep(5000);
}
public void m2(){
System.out.println(b);
}
public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws InterruptedException{
TT t1=new TT();
Thread t2=new Thread();
t2.start();
t1.m2();
}
} 这是马士兵讲的线程同步面试题 ,视频上结果是b=1000 而我运行却是b=100 我晕 这是为什么啊线程sleep后 处于什么状态啊! 假设sleep后线程是等待状态,那么加了 synchronized 后,此线程依旧不释放资源,就应该是b=100啊
t2.start();没T1什么事,T1依然是个Runnable
t2.start()跟t1没有半毛钱的关系你似乎忘记将t1递给t2做参数了粗心的家伙
Thread t2=new Thread();
t2.start();
t1.m2();
t1和t2一点关系都没有么
* 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)
*/
public void run() {
if (target != null) {
target.run();
}
}
原生的Thread类实例,你去start之后,会调用run()方法,但这个方法的默认实现请看上面的代码
那么这个target是怎么进去的呢,其实就在构造里面我们做线程编程无非就是2个方法
1.扩展Thread类,并覆盖其run()方法,这样以来,真正干的事情在我们新写的run()方法里面,原来的什么target判定啊,全都成浮云了
当然,你可以写个类扩展,也可以用匿名内部类的方式
2.就是实现Runnable接口,这个接口没别的东西,就一个run()方法,明眼人应该能看出来了,为什么我们的Runnable不能直接start(),而必须借助Thread来实现,其实就是因为我们的类,仅仅包装了一个run()方法——一个处理过程,我们要把这个过程注入到Thread类中,这着叫“借尸还魂”这个过程我给起了个名字——行为注入万恶的闭包,其实都可以这么处理掉的