62,623
社区成员
发帖
与我相关
我的任务
分享
public class TT implements Runnable {
int b = 100;
// 如果m2方法没有加关键字synchronized,就可以在m1锁的同时访问里面的任何东西,
// 但是如果加了锁就不可以访问b,必须等m1完成以后.
public synchronized void m1() throws Exception {
b = 1000;
// Thread.sleep(5000);
System.out.println("m1 " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("m2 " + b);
}
public void run() {
try {
m1();
} catch (Exception ex) {
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}
TT tt = new TT(); // 一个主线程的实例
Thread t = new Thread(tt); // 开启一个新的子线程
t.start(); // 子线程run,但是这个时候主线程有着优先权(或者有很短的切换时间),而且可以立即执行到tt.m2();
tt.m2(); // 很快执行完毕,接着m1()也顺利执行完毕
TT tt = new TT(); // 一个主线程的实例
Thread t = new Thread(tt); // 开启一个新的子线程
Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // 让主线程的优先级别最低
t.setPriority(Thread.MAX_PRIORITY); // 让子线程的优先级最高