//改成執行緒聯合方式!!
import java.util.*;
class RWthread
{
public static void main(String args[])
{
String readName="讀執行緒",writeName="寫執行緒";
ReadWrite rw=new ReadWrite(readName,writeName);
Thread read,write;
read=new Thread(rw);
write=new Thread(rw);
read.setName(readName);
write.setName(writeName);
read.start();
write.start();
}
}
class ReadWrite implements Runnable
{
String ID=null;
String name=null;
String readName,writeName;
boolean flag=false;
public ReadWrite(String s1,String s)
{
readName=s1;
writeName=s;
}
public void run()
{
readOrWrite();
}
public synchronized void readOrWrite() //同步方法
{
if(Thread.currentThread().getName().equals(readName))
{
Scanner reader=new Scanner(System.in);
while(true)
{
if(flag)
{
try{
wait();
}catch(InterruptedException e){}
}
System.out.println("請輸入學號:");
ID=reader.nextLine();
if(ID.equals("finish"))
{
System.out.println("\n讀執行緒和寫執行緒作業結束!");
flag=true;
notify();
reader.close();
return;
}
System.out.println("請輸入姓名:");
name=reader.nextLine();
flag=true;
notify();
}
}
else if(Thread.currentThread().getName().equals(writeName))
{
while(true)
{
if(!flag)
{
try{
wait();
}catch(InterruptedException e){}
}
if(ID.equals("finish"))
return;
System.out.println("\n輸出學號:"+ID+",輸出姓名:"+name);
System.out.println();
flag=false;
notify();
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230415.html
標籤:Java相關
上一篇:Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
