如下,是一个用object lock对wait/notify的操作,
请问如果把run定义为synchronized的话,该怎么写?
可不可以直接用run的synchronized对wait/notifyAll操作?
(书上程序:)
class WaitingThread extends Thread{
public Object lock;
public WaitingThread(String name){
super(name);
}
public void run(){
while(!this.isInterrupted()){
doSomething();
}
}
public void doSomething(){
synchronized(lock){
try{
System.out.println("Wait!");
lock.wait();
}catch(InterruptedException ie){
System.out.println("WaitingThread interrupted");
}
for(int i = 0; i < 5; i++){
System.out.println("Thread" + this.getName() + "is running");
}
}
}
}class FirstThread extends Thread{
public Object lock;
public FirstThread(String name){
super(name);
}
public void run(){
while(!this.isInterrupted()){
doSomething();
}
}
public void doSomething(){
synchronized(lock){
try{
this.sleep(200);
}catch(InterruptedException ie){
System.out.println("FirstThread interrupted");
}
for(int i = 0;i < 5; i++){
System.out.println("Thread" + this.getName() + "is running");
}
lock.notifyAll();
}
}
}public class WaitingThreadExample{
public static void main(String args[]){
WaitingThreadExample ex = new WaitingThreadExample();
WaitingThread thread1 = new WaitingThread("Waiting");
thread1.lock = ex;
FirstThread thread2 = new FirstThread("First");
thread2.lock = ex;
thread1.start();
thread2.start();
}
}
请问如果把run定义为synchronized的话,该怎么写?
可不可以直接用run的synchronized对wait/notifyAll操作?
(书上程序:)
class WaitingThread extends Thread{
public Object lock;
public WaitingThread(String name){
super(name);
}
public void run(){
while(!this.isInterrupted()){
doSomething();
}
}
public void doSomething(){
synchronized(lock){
try{
System.out.println("Wait!");
lock.wait();
}catch(InterruptedException ie){
System.out.println("WaitingThread interrupted");
}
for(int i = 0; i < 5; i++){
System.out.println("Thread" + this.getName() + "is running");
}
}
}
}class FirstThread extends Thread{
public Object lock;
public FirstThread(String name){
super(name);
}
public void run(){
while(!this.isInterrupted()){
doSomething();
}
}
public void doSomething(){
synchronized(lock){
try{
this.sleep(200);
}catch(InterruptedException ie){
System.out.println("FirstThread interrupted");
}
for(int i = 0;i < 5; i++){
System.out.println("Thread" + this.getName() + "is running");
}
lock.notifyAll();
}
}
}public class WaitingThreadExample{
public static void main(String args[]){
WaitingThreadExample ex = new WaitingThreadExample();
WaitingThread thread1 = new WaitingThread("Waiting");
thread1.lock = ex;
FirstThread thread2 = new FirstThread("First");
thread2.lock = ex;
thread1.start();
thread2.start();
}
}
为什么不可以,试试先
while(!this.isInterrupted()){
doSomething();
}
}
但这并不合理,太容易出现问题