?? arraysynchronized.java
字號:
package cwq4;
import javax.swing.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class ArraySynchronized {
private int[] array = new int[]{-1,-1,-1,-1,-1,-1};
private boolean writeable = true;
private int times;
//private JTextArea textarea;
public ArraySynchronized() {this.times = 5;}
public void settimes(int value){
this.times = value;
}
public int gettimes(){
return this.times;
}
public synchronized void setSharedArray(JTextArea output)
{
while ( !writeable ) { // not the producer's turn
// thread that called this method must wait
try { wait(); }
// process Interrupted exception while thread waiting
catch ( InterruptedException exception ) {
exception.printStackTrace();
}
}
// set new shared array values
for (int i =0; i<6; i++)
this.array[i] = (int)(Math.random()*100);
//System.out.println( Thread.currentThread().getName() +
// "************* setting shared array to: " + array[0]+"," + array[1]+","
// + array[2]+","+ array[3]+","+ array[4]+","+ array[5]+".");
output.append
("write thread setting shared array to: "
+ array[0]+"," + array[1]+"," + array[2]+","+ array[3]+","
+ array[4]+","+ array[5]+".\n");
// indicate that producer cannot store another value until
// a consumer retrieve current sharedInt value
writeable = false;
// tell a waiting thread to become ready
notify();
}
public synchronized void getAndsortSharedArray(JTextArea output)
{
while ( writeable ) { // not the consumer's turn
// thread that called this method must wait
try { wait(); }
// process Interrupted exception while thread waiting
catch ( InterruptedException exception ) {
exception.printStackTrace();
}
}
// indicate that producer cant store another value
// because a consumer just retrieved sharedInt value
int[] temp = this.array;
int tempint;
writeable = true;
for (int i = 0; i < 6; i++) {
for (int j = i; j < 6; j++) {
if (temp[j] < temp[i]) {
tempint = temp[i];
temp[i] = temp[j];
temp[j] = tempint;
}
}
}
// tell a waiting thread to become ready
notify();
output.append("read thread sort shared array to: " + temp[0]+"," + temp[1]+","
+ temp[2]+","+ temp[3]+","+ temp[4]+","+ temp[5]+".\n\n" );
}
}//end class ArraySynchronized
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -