Java synchronized

来源:互联网 发布:淘宝的化妆品是正品吗 编辑:程序博客网 时间:2024/04/30 02:17
public class MyTest {public void m4tab() {// TODO Auto-generated method stubsynchronized (this) {for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName()+ " synchronized " + i);}}}public void m4t1() {int i = 5;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}public void m4t2() {int i = 5;synchronized (this) {while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}}public void m4t3() {int i = 5;synchronized (this) {while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}}public static void main(String[] args) {MyTest mTest = new MyTest();Thread ta = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubmTest.m4tab();}}, "A");Thread tb = new Thread(new Runnable() {public void run() {mTest.m4tab();}}, "B");Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubmTest.m4t1();}}, "T1");Thread t2 = new Thread(new Runnable() {public void run() {mTest.m4t2();}}, "T2");Thread t3 = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubmTest.m4t3();}}, "T3");ta.start();tb.start();t1.start();t2.start();t3.start();}}

0 0
原创粉丝点击