public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//分开一条线程执行RUN方法
tt.m2();主线程继续向下执行
System.out.println(tt.b);
}
}以上是代码。能给我画下详细的流程图吗。先执行的start()为什么最后的值是1000?
而且为什么先执行m2再扫行m1
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//分开一条线程执行RUN方法
tt.m2();主线程继续向下执行
System.out.println(tt.b);
}
}以上是代码。能给我画下详细的流程图吗。先执行的start()为什么最后的值是1000?
而且为什么先执行m2再扫行m1
2.Thread t = new Thread(tt)创建线程对象
3.启动线程t.start();
4.线程开始同步
5.执行线程tt.m2();
6.synchronized方法是同步
7.线程休眠Thread.sleep(2500);过后在进行操作
8.线程同步在执行Thread.sleep(5000);又一次休眠
9.打印结果
public class Mm implements Runnable {
int b = 100; public synchronized void m1() throws Exception{
System.out.println("调用m1");
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
System.out.println("m1结束");
} public synchronized void m2() throws Exception {
System.out.println("调用m2");
Thread.sleep(2500);
b = 2000;
System.out.println("m2结束");
} public void run() {
try {
System.out.println("调用run");
m1();
} catch(Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
Mm tt = new Mm();
Thread t = new Thread(tt);
t.start();
System.out.println("主线程1");
tt.m2();
System.out.println("主线程2\n"+tt.b);
} }
这个代码和上一个基本一样但是为什么结果却是
主线程1
调用run
调用m2
m2结束
调用m1
主线程2
2000
b = 1000
m1结束
呢?多打印了几个东西就变成2000了?第一个代码得到的是1000啊 如果把这个讲清楚立即送分
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//分开一条线程执行RUN方法System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");System.out.println("xx");
tt.m2();主线程继续向下执行
System.out.println(tt.b);
}
}