synchronizedブロック及び方法応用
1537 ワード
package test;
class Obj implements Runnable {
public void fun1() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " ");
try {
System.out.println("fun1() ");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ");
}
}
public synchronized void fun2() {
System.out.println(Thread.currentThread().getName() + " ");
System.out.println("fun2() ");
System.out.println(Thread.currentThread().getName() + " ");
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("T1")
|| Thread.currentThread().getName().equals("T3")) {
fun1();
} else {
fun2();
}
}
}
public class ThreadSynchronizedTest {
/**
* @param args
*/
public static void main(String[] args) {
Obj obj1 = new Obj(),
obj2 = new Obj();
Thread T1 = new Thread(obj1), // T1,T2 , Obj1
T2 = new Thread(obj1),
T3 = new Thread(obj2); // T2,T3 , Obj1,Obj2
T1.setName("T1");
T2.setName("T2");
T3.setName("T3");
T1.start();
T2.start();
T3.start();
}
}