【发布时间】:2014-07-01 10:33:51
【问题描述】:
我尝试使用静态布尔变量来锁定和解锁两个同步线程。 于是我写了如下代码:
public class Main {
public static void main(String[] args){
//MyObject lock = new MyObject();
Thread1 t1 = new Thread1(100,'#');
Thread1 t2 = new Thread1(100,'*');
t1.start();
t2.start();
}
}
public class Thread1 extends Thread {
public static boolean lock;
int myNum;
char myChar;
public Thread1(int num, char c){
myNum = num;
myChar = c;
lock = false;
}
public synchronized void run(){
System.out.println(getName() + " is runing");
while (Thread1.lock == true){
System.out.println(getName() + " is waiting");
try{wait();}
catch(InterruptedException e){}
}
Thread1.lock = true;
for(int i = 0; i<myNum; i++){
if(i%10==0)
System.out.println("");
System.out.print(myChar);
}
Thread1.lock = false;
notifyAll();
}
}
可能我做得不对,因为只有一个线程正在打印“mychar”,而另一个线程只是进入 wait() 并且在我执行 notifyAll() 时没有醒来。 我认为这可能是为整个类使用静态布尔变量的好方法,而不是每次都更改它并调用 notifyAll() 来检查其他对象中的这个标志...
输出示例:
Thread-0 is runing
Thread-1 is runing
Thread-1 is waiting
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########
【问题讨论】:
-
如果你想串行运行线程,最好使用循环而不是线程。
-
学习多线程的经典例子是实现生产者/消费者线程。生产者生产东西并通知消费者;同时消费者在消费后等待。
标签: java multithreading synchronized