public class TTT implements Runnable {
int b = 100; public static void main(String[] args) throws InterruptedException {
TTT tt = new TTT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
} private synchronized void m2() throws InterruptedException {
System.out.println("m2=" + b);
b = 2000;
} public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public synchronized void m1() throws InterruptedException {
System.out.println("开始的b=:" + b);
b = 1000;
Thread.sleep(5000);
System.out.println("m1=" + b);
}
}我睡眠了5秒 前面的b=2000为什么改变不了m1的值
int b = 100; public static void main(String[] args) throws InterruptedException {
TTT tt = new TTT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
} private synchronized void m2() throws InterruptedException {
System.out.println("m2=" + b);
b = 2000;
} public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public synchronized void m1() throws InterruptedException {
System.out.println("开始的b=:" + b);
b = 1000;
Thread.sleep(5000);
System.out.println("m1=" + b);
}
}我睡眠了5秒 前面的b=2000为什么改变不了m1的值
解决方案 »
- java菜鸟的烦恼
- 能不能把一个类的东西分布到多个文件中去?
- java正则问题?
- JTextField失去焦点遇到的问题
- 有没有大陆版本的TIJ???
- 求接触mvc的人给小妹解决哈这个小问题啊!
- 求解数组相关算法!
- 求助:Mina - WriteFuture的awaitUninterruptibly等不到返回结果
- 终于鼓起勇气认真学习JAVA了,先散点分混个脸熟,各位帮忙捧捧场吧~~~
- 我在调用Constructor的时候,抛出个异常,看不太懂
- 有关Arraylist问题,请帮我改几行代码
- 请问java中连接数据库(如Access、MySQL),能否在数据库中设置不属于java基本类型的日期型等类型?
public static void main(String[] args) throws InterruptedException {
TTT tt = new TTT();
Thread t = new Thread(tt);
t.start();
Thread.sleep(6000);//要睡得比m1长
tt.m2();
System.out.println(tt.b);
}
t.join(); // 等待子线程结束
tt.m2();
为什么一定要让主线程 比子线程睡的时间要长 当b=2000 子线程正在睡眠 这个时候 b=2000 不会改变b的值么?
public class TTT implements Runnable {
int b = 100; public static void main(String[] args) throws InterruptedException {
TTT tt = new TTT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
} private void m2() throws InterruptedException {
System.out.println("m2=" + b);
b = 2000;
} public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public synchronized void m1() throws InterruptedException {
System.out.println("开始的b=:" + b);
b = 1000;
Thread.sleep(5000);
System.out.println("m1=" + b);
}
}
那现在的执行过程 又有那些可能啊?
运行m2中的b=2000这句的时候,子线程没有在睡眠,子线程在“阻塞”或者“可运行“状态。“为什么一定要让主线程 比子线程睡的时间要长”这是为了让子线程先于主线程醒过来,也就是让b=1000在前,b=2000在后,这样就能看到最终结果是2000了不知我说明白了没
一般来说,在实例方法前加synchronized会以这个类实例为锁对象,所以任何方法成功调用这个方法,会拥有这个对象的锁,别的线程就只能等待。
m1和m2两个方法都是synchronized的,可见你想让他们达到互斥的作用。
按照你的写法,m1和m2没有特定的执行顺序。