多线程死锁代码

Posted windzly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程死锁代码相关的知识,希望对你有一定的参考价值。

package test;

import java.awt.List;
import java.awt.image.AreaAveragingScaleFilter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.io.BufferedInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import javax.security.auth.callback.LanguageCallback;
import javax.swing.text.StyledEditorKit.BoldAction;

class Lock {
	public static final Object alock = new Object();
	public static final Object block = new Object();
}

class Zhuzhu implements Runnable {
	public String c;
	private boolean flag;
	private int num = 100;

	public Zhuzhu(boolean flag) {
		this.flag = flag;
	}

	
	Object object = new Object();

	public void run() {
		if (flag == true) {
			while(true)
			synchronized (Lock.alock) {
				System.out.println("if...alock");
				synchronized (Lock.block) {
					System.out.println("if....block");
				}
			}
		}
		else {
			while(true)
			synchronized (Lock.block) {
				System.out.println("else...block");
				synchronized (Lock.alock) {
					System.out.println("else....alock");
				}
			}
		}
	}

}


public class Main {

	public static void main(String[] args) throws Exception {

		Scanner scanner = new Scanner(new BufferedInputStream(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

		Zhuzhu c = new Zhuzhu(true);
		Zhuzhu d = new Zhuzhu(false);
		Thread t1 = new Thread(c);
		Thread t2 = new Thread(d);

		t1.start();
		t2.start();
		
	}
}

  

以上是关于多线程死锁代码的主要内容,如果未能解决你的问题,请参考以下文章

怎么处理JAVA多线程死锁问题?

使用多线程代码在一张表上发生 MySQL 死锁

Java多线程-死锁简述

死锁的概念以及处理方式

Java多线程产生死锁的一个简单案例

Linux:详解多线程(线程安全互斥和死锁)