日期:2014-05-20  浏览次数:20637 次

初学线程,帮忙看下
import java.util.*;
public class i_othread
{
public static void main(String args[])
{  
ipthread thread_1=new ipthread(); //输入线程
opthread thread_2=new opthread(); //输出线程
thread_1.start();
thread_2.start();
}
}
class ipthread extends Thread
{

public ipthread()
{
System.out.println("请输入:");
}
public void run()
{
Scanner input=new Scanner(System.in);
String name=input.nextLine();
}
}
class opthread extends Thread
{
public opthread()
{
  System.out.println("输出结果为:");

}
public void run()
{  
System.out.print(name);
}
}


我想要的目的很简单,就是我一边输入它一边输出,请大家帮忙修改一下程序,谢谢了


------解决方案--------------------
name 访问有问题,他们互相不认识
我再改改代码,等等
------解决方案--------------------
不知道是不是最优解,你看看吧。

import java.util.Scanner;

class Q{
private String name="";
boolean b=false;

public synchronized void put() throws InterruptedException{
if(b){
wait();
}
Scanner input = new Scanner(System.in);
System.out.println("请输入");
name = input.next();
b=true;
notify();

}
public synchronized void get() throws InterruptedException{

if(!b){

wait();
}
System.out.println("输入的是:"+name);
b=false;
notify();

}
}
class Input implements Runnable{
Q q = null;
public Input(Q q){
this.q=q;
}
public void run(){
int i=0;
while(true){
try {
q.put();
i++;
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
class Output implements Runnable{
Q q = new Q();
public Output(Q q){
this.q=q;
}
public void run(){
while(true){

try {
q.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class bb{
public static void main(String args[]){
Q q = new Q();
Input p = new Input(q);
Thread t = new Thread(p);
Output c = new Output(q);
Thread t1 = new Thread(c);
t.start();
t1.start();
}
}
------解决方案--------------------
首先要说的是:类名,一般是首个字母大写,并且词与词之间不用下划线来隔开 !
比如那个类名为i_othread 应写成 IOThread

下面的程序,并没有修改LZ写的那些类名,你可以自己修改!

import java.util.*; 
public class i_othread { 
public static void main(String args[]) throws Exception { 
Outer outer = new Outer();
Outer.ipthread thread_1=outer.new ipthread();
Outer.opthread thread_2=outer.new opthread();

}
 
class Outer { 
private static String name ; 
public synchronized void readInput() {
System.out.printf("\n请输入:\n");
Scanner input=new Scanner(System.in); 
name=input.nextLine(); 

}
public synchronized void printInput() {
System.out.print("输出结果为:"); 
System.out.println(name); 
}

public class ipthread extends Thread { 
public ipthread() { 
start(); 

public void run() {
try {
int i =5;
while(i-- != 0) {
readInput();


}catch(Exception e) {
}