多线程编程实例

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......
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值