# JAVA 实验六:线程

# 实验目的

  1. 掌握线程的概念。
  2. 掌握线程的创建方法。
  3. 掌握线程的常用方法。
  4. 掌握线程同步的方法
  5. 掌握线程联合的方法。

# 实验内容

将实验 6 文件夹中所附的源程序 “RWthread.java” 改为用线程联合实现。

# 实验代码

# 原 RWthread.java 代码

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();
			}
		}
	}  
}

# 改成线程联合实现后

import java.util.*;
class RWthread
{
	public static void main(String args[])
	{
		ReadWrite rw=new ReadWrite();
		rw.write.start();
	}
}
class ReadWrite implements Runnable
{
	String ID=null;
	String name=null;
	boolean flag=false;
	String readName="读线程",writeName="写线程";
	Thread read,write;
	ReadWrite()
	{
		write=new Thread(this);
		write.setName(writeName);
	}
	public void run()
	{
		if(Thread.currentThread().getName().equals(readName)) 
		{
				Scanner reader=new Scanner(System.in);
				System.out.println("请输入学号:");
				ID=reader.nextLine();
				if(ID.equals("finish"))
				{
					System.out.println("\n读线程和写线程工作结束!");
					
					reader.close();
					return;
				}
				System.out.println("请输入姓名:");
				name=reader.nextLine();	
		}
		else if(Thread.currentThread().getName().equals(writeName))
		{
			while(true)
			{
				if(read!=null)
				{
					read.stop();
				}
				read=new Thread(this);
				read.setName(readName);
				read.start();
					try{
						read.join();    
					}catch(InterruptedException e){}
				if(ID.equals("finish"))
					return;
				System.out.println("\n输出学号:"+ID+",输出姓名:"+name);
				System.out.println();
			}
		}
	}
}
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Lavender 微信支付

微信支付

Lavender 支付宝

支付宝

Lavender 贝宝

贝宝