主线程和子线程同时使用一个对象(this对象)
package thread;
public class Thread_7 {
public static void main(String[] args) throws InterruptedException {
Mythread m = new Mythread();
Thread t = new Thread(m);
t.start();
m.m1("主线程1");
Thread.sleep(1000);
m.m2("主线程2");
}
}
class Mythread implements Runnable{
private int b = 100;
public synchronized void m1(String name){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("m1:"+b+""+name);
}
public synchronized void m2(String name){
/*Thread.sleep(1000);*/
b = 200;
System.out.println("m2:"+b+""+name);
}
@Override
public void run() {
System.out.println("进入子线程");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m1("子线程");
}
}