package com.xiaozhi.threads;
public class Test5 {
public static void main(String[] args) {
MyRunable myRunable=new MyRunable();
Thread thread1=new Thread(myRunable);
Thread thread2=new Thread(myRunable);
thread1.start();
thread2.start();
}
}
class MyRunable implements Runnable {
private Object locka=new Object();
private Object lockb=new Object();
@Override
public void run() {
while(true)
{
if (Thread.currentThread().getName().equals("Thread-0"))
{
synchronized (locka)
{
System.out.println("Thread-0------------------locka");
synchronized (lockb)
{
System.out.println("Thread-0------------------lockb");
}
}
}
else if (Thread.currentThread().getName().equals("Thread-1"))
{
synchronized (lockb)
{
System.out.println("Thread-1------------------lockb");
synchronized (locka)
{
System.out.println("Thread-1------------------locka");
}
}
}
}
}
}
多次运行,出现死锁的时刻不同
将共同使用的数据封装成一个对象,谁拥有数据谁负责对外提供操作它们的方法。
package com.xiaozhi.threads;
public class Test5 {
public static void main(String[] args) {
LockInstance lockInstance =new LockInstance();
Thread thread1=new Thread(new MyRunnable1(lockInstance));
Thread thread2=new Thread(new MyRunnable2(lockInstance));
thread1.start();
thread2.start();
}
}
class LockInstance{
private Object locka=new Object();
private Object lockb=new Object();
public Object getLocka() {
return locka;
}
public void setLocka(Object locka) {
this.locka = locka;
}
public Object getLockb() {
return lockb;
}
public void setLockb(Object lockb) {
this.lockb = lockb;
}
}
class MyRunnable1 implements Runnable {
private LockInstance lockInstance;
public MyRunnable1(LockInstance lockInstance) {
super();
this.lockInstance = lockInstance;
}
@Override
public void run() {
while(true)
{
synchronized (lockInstance.getLocka())
{
System.out.println("Thread-0------------------locka");
synchronized (lockInstance.getLockb())
{
System.out.println("Thread-0------------------lockb");
}
}
}
}
}
class MyRunnable2 implements Runnable {
private LockInstance lockInstance;
public MyRunnable2(LockInstance lockInstance) {
super();
this.lockInstance = lockInstance;
}
@Override
public void run() {
while(true)
{
synchronized (lockInstance.getLockb())
{
System.out.println("Thread-1------------------lockb");
synchronized (lockInstance.getLocka())
{
System.out.println("Thread-1------------------locka");
}
}
}
}}