主線程和子線程同時使用一個對象(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("子線程");
}
}