线程中其他方法以及死锁

多线程中还有其他调度方法:

Thread.yield();//相当于在相同优先级的线程内部再进行 优先级的区分

Thread.sleep进行调度,让当前线程睡眠---会释放出CPU资源(但是不会释放对象锁)

t2.interrupt();// 强制唤醒 t2线程----t2线程会从睡眠状态切换到Runnable状态

利用优先级进行相对调度
//t1.setPriority(5);//线程优先级共有10级,越大越优先
//t2.setPriority(7);
一个死锁的例子:

public class ThreadA implements Runnable{
private S1 s1 = null;
private S2 s2 = null;

public ThreadA(S1 s1, S2 s2) {
this.s1 = s1;
this.s2 = s2;
}


@Override
public void run() {
System.out.println("ThreadA begin......");
synchronized (s1) {
System.out.println("ThreadA拿到对象锁1:"+s1.a);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadA睡醒,准备拿对象锁2...");
synchronized (s2) {
System.out.println("ThreadA手握对象锁1和锁2,进行工作..."+s2.a);
}
}
}


}

public class ThreadB implements Runnable{
private S1 s1 = null;
private S2 s2 = null;

public ThreadB(S1 s1, S2 s2) {
this.s1 = s1;
this.s2 = s2;
}


@Override
public void run() {
System.out.println("ThreadB begin......");
synchronized (s2) {
System.out.println("ThreadB拿到对象锁2:"+s2.a);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadB睡醒,准备拿对象锁1...");
synchronized (s1) {
System.out.println("ThreadB手握对象锁1和锁2,进行工作..."+s1.a);
}
}
}


}

public class Demo2 {
public static void main(String[] args) {
S1 s1 = new S1();
S2 s2 = new S2();

Thread b = new Thread( new ThreadB(s1,s2) );
Thread a = new Thread( new ThreadA(s1, s2) );

b.start();
a.start();
}
}


class S1{
public int a=1;
}
class S2{
public int a=2;
}


多个对象在线程中处理时,可能会导致多个类分别抢到不同的锁,在进行复杂调度的情况下,无法返回对象锁,而导致死锁。

解决办法:我们需要将多个对象锁包装成一个对象锁,这样,锁连在一起,则可以解决死锁的情况

第二个例子:

ublic class ThreadB implements Runnable{
private S s = null;


public ThreadB(S s) {
super();
this.s = s;
}

@Override
public void run() {
System.out.println("ThreadB begin......");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadB 睡后继续运行....");
synchronized (s) {
  s.a = 100;
  System.out.println("ThreadB 已经完成对资源s.a的赋值,s.a="+s.a);
}

}
}

public class ThreadA implements Runnable{
private S s = null;
private Thread b=null;

public ThreadA(S s, Thread b) {
this.s = s;
this.b = b;
}


@Override
public void run() {
System.out.println("ThreadA begin......");
synchronized (s) {
System.out.println("ThreadA拿到对象锁,进入同步块....");

try {
b.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadA, a="+s.a);
}
}


}

public class Demo1 {
public static void main(String[] args) {
S s = new S();
Thread b = new Thread( new ThreadB(s) );
Thread a = new Thread( new ThreadA(s, b) );

b.start();
a.start();
}
}


class S{
public int a=0;
}

在多个线程进行互相调度时,sleep()无法返回对象锁,会导致死锁。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值