📄 deadlock.java
字号:
/**
* @(#)DeadLock.java
*
*
* @author
* @version 1.00 2007/12/1
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Win extends JFrame implements Runnable{
JPanel p1,p2;
JLabel lab1,lab2;
JTextArea text1,text2;
Thread trdA,trdB;
private int accounts[]={1000,1000};
Win() {
setLayout(new GridLayout(2,1));
p1=new JPanel();
p1.setLayout(new BorderLayout());
lab1=new JLabel("Account Information");
text1=new JTextArea(5,40);
p1.add(lab1,BorderLayout.NORTH);
p1.add(new JScrollPane(text1),BorderLayout.CENTER);
p2=new JPanel();
p2.setLayout(new BorderLayout());
lab2=new JLabel("Thread Information");
text2=new JTextArea(5,40);
p2.add(lab2,BorderLayout.NORTH);
p2.add(new JScrollPane(text2),BorderLayout.CENTER);
add(p1); add(p2);
trdA=new Thread(this);
trdA.setName("A");
trdB=new Thread(this);
trdB.setName("B");
trdA.start();
trdB.start();
setSize(400,700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
public void run() {
while (true) {
int amount=(int) (1500*Math.random());
String s1=Thread.currentThread().getName();
String s2=(s1.equals("A")?"B":"A");
text2.append("Thread "+s1+" sends $"+amount+" into "+s2+"\n");
System.out.println("Thread "+s1+" sends $"+amount+" into "+s2+"\n");
try {
//System.out.println(s1+"开始休息...");
Thread.sleep(20);
//System.out.println(s1+"醒来了!");
}
catch (InterruptedException ie) {
System.err.println("interruption in sleeping"+ie);
}
//System.out.println(s1+"开始转账...");
transfer(amount);
//System.out.println(s1+"转帐完毕!");
}
}
public synchronized void transfer(int amount) {
text1.append("Account A: $"+accounts[0]+"\n");
text1.append("Account B: $"+accounts[1]+"\n");
String s1=Thread.currentThread().getName();
String s2=(s1.equals("A")?"B":"A");
int from=(s1.equals("A")?0:1);
int into=1-from;
text1.append("=> $"+amount+" from"+s1+" to "+s2+"\n");
while (accounts[from]<amount) {
try {
System.out.println(s1+"由于金额少所以等待...");
wait();
System.out.println(s1+"金额够了,被唤醒");
}
catch (InterruptedException ie) {
System.err.println("Error: "+ie);
}
}
accounts[from]-=amount;
accounts[into]+=amount;
notify();
}
}
public class DeadLock {
/**
* Creates a new instance of <code>DeadLock</code>.
*/
public DeadLock() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Win();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -