【多线程】synchronized同步方法

来源:互联网 发布:c语言指针编程题 编辑:程序博客网 时间:2024/05/18 17:58
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;@Overridepublic 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;}}