只用一个输出函数, 并对此函数使用同步关键字synchronized
static int count = 0;
static synchronized void out() {
System.out.println(count++);
}
static int count = 0;
static synchronized void out() {
System.out.println(count++);
}
调试欢乐多
下面的例子:
class One
{
synchronized void display(int num)//synchronized为同步方法
{
System.out.print(""+num);
try{
Thread.sleep(1000);//睡眠1000毫秒
}
catch(InterruptedException e){
System.out.println("中断");
}
System.out.println("完成");
}
}
class Two implements Runnable //实现接口
{
int number;
One one;
Thread t;
public Two(One one_num,int n)
{
one=one_num;
number=n;
t=new Thread(this);
t.start();
}
public void run()
{
one.display(number);
}
}
public class Synch
{
public static void main(String args[])
{
One one=new One();
int digit=10;
Two s1=new Two(one,digit++);//11
Two s2=new Two(one,digit++);//12
Two s3=new Two(one,digit++);//13
try{
s1.t.join();
s2.t.join();
s3.t.join();
}
catch(InterruptedException e){
System.out.println("中断");
}
}
}
private MySharedObject so; public TestThread(MySharedObject so) {
this.so = so;
for(int i = 0; i < 5; i++){
OutputThread t0 = new OutputThread(so, i);
}
} public static void main(String[] args) {
MySharedObject so = new MySharedObject();
TestThread t0 = new TestThread(so);
}
}//////
class OutputThread implements Runnable {
private Thread self = null;
private MySharedObject so;
private int number;
private boolean running = true; public OutputThread(MySharedObject so, int number) {
this.so = so;
this.number = number;
self = new Thread(this);
self.start();
} public void run() {
while(so.hasNext()){
System.out.println("get in thread " + number + ": " + so.get());
}
}
} class MySharedObject {
private int[] available = new int[100];
private int pos = 0;
private int count = 0; public MySharedObject(){
for(int i = 0; i < 100; i++){
available[i] = i;
}
}
public synchronized int get() {
count++;
while ( count >= 2) {
try {
wait();
} catch (InterruptedException e) {
}
}
count--;
notifyAll();
return available[pos++];
} public synchronized boolean hasNext() {
return pos < 100 ;
}
}
不知道能不能用, 你看看吧