public class SynchronizedTest2 {
public static void main(String[] args) {
ThreadTest t1 = new ThreadTest();
new Thread(t1).start();
new Thread(t1).start();
System.out.println(t1.call());
}
}
class ThreadTest implements Runnable{
private int x;
private int y;
@Override
public synchronized void run() {
for(int i=0;i<4;i++){
x++;
y++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("線程出錯了!!!");
}
System.out.println(Thread.currentThread().getName() + " x==" + x + ",y==" + y + " " + i);
}
}
public synchronized String call(){
String name = Thread.currentThread().getName();
return "hellow " + name;
}
}
【多線程】synchronized同步方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.