package jiekou.com.cn;
public class Syn {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread123 thread = new Thread123();
Thread1 thread1 = new Thread1();
Thread tb = new Thread(thread, "B");
Thread ta = new Thread(thread, "A");
Thread notT = new Thread(thread1);
ta.start();
tb.start();
notT.start();
}
}
class Thread123 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "synchronized loop" + i);
}
}
}
}
class Thread1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ "not synchronized loop" + i);
}
}
public class Syn {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread123 thread = new Thread123();
Thread1 thread1 = new Thread1();
Thread tb = new Thread(thread, "B");
Thread ta = new Thread(thread, "A");
Thread notT = new Thread(thread1);
ta.start();
tb.start();
notT.start();
}
}
class Thread123 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "synchronized loop" + i);
}
}
}
}
class Thread1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ "not synchronized loop" + i);
}
}
}
---------------------
Thread-0not synchronized loop0
Asynchronized loop0
Thread-0not synchronized loop1
Thread-0not synchronized loop2
Thread-0not synchronized loop3
Thread-0not synchronized loop4
Asynchronized loop1
Asynchronized loop2
Asynchronized loop3
Asynchronized loop4
Bsynchronized loop0
Bsynchronized loop1
Bsynchronized loop2
Bsynchronized loop3
Bsynchronized loop4