首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

多线程编程范例

2013-03-21 
多线程编程实例package threadpublic class TestSync implements Runnable{Timer timer new Timer()pu

多线程编程实例
package thread;

public class TestSync implements Runnable{

Timer timer = new Timer();
public static void main(String args[]){
TestSync ts = new TestSync();
Thread t1 = new Thread(ts);
Thread t2 = new Thread(ts);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();

}
public void run(){
timer.add(Thread.currentThread().getName());
}
}

class Timer{
private static int num=0;

//没有synchronized关键字,执行结果:
//t1,你是第2个使用timer的线程!
//t2,你是第2个使用timer的线程!

//有synchronized关键字,执行结果:
//t1,你是第1个使用timer的线程!
//t2,你是第2个使用timer的线程!

//synchronized可以对需要同步执行的代码进行同步
//加在代码块上和方法上,那么同步的粒度将会发生改变
public synchronized void add(String name){
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+",你是第"+num+"个使用timer的线程!");
}
}



package thread;

public class DeadLockTest implements Runnable{

public int flag = 1;

static Object o1 = new Object(),o2 = new Object();

public void run() {

System.out.println("flag = "+ flag);

if(flag ==1){
synchronized(o1){
try {
System.out.println("lock o1,waitting for o2,sleeping......");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o2){
System.out.println("1");
}
}
}

if(flag ==2){
synchronized(o2){
try {
System.out.println("lock o2,waitting for o1,sleeping......");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o1){
System.out.println("2");
}
}
}

}//run block

public static void main(String args[]){
DeadLockTest dl1 = new DeadLockTest();
DeadLockTest dl2 = new DeadLockTest();
dl1.flag = 1;
dl2.flag = 2;
Thread t1 = new Thread(dl1);
Thread t2 = new Thread(dl2);
t1.start();
t2.start();
//程序一直处于挂起,等待状态。。。。。。
//flag = 1
//lock o1,waitting for o2,sleeping......
//flag = 2
//lock o2,waitting for o1,sleeping......
}
}

热点排行