新手初学多线程,对多线程理解不够好.刚写一个小程序,高手看看错误在哪里
题目要求: 5个读线程,2个写线程,要求从5个读线程读入字符串,转化成大写后,放入写线程小弟的感觉.重点.就是如果让读线程不能和两个写线程冲突问题.我的想法是写了两个写线程的CLASS,必须JOIN后才能继续(也就是不冲突),在读线程里通过取一个随机数,决定放入第一个写线程还是第二个写线程
小弟是以C++入门的,对JAVA完全有点晕,本身就不会多线程,现在用JAVA写就更糊涂了.求改错.先谢谢了...
程序代码:
public class ReadThread implements Runnable//读线程 { private string name; public ReadThread(string name1) { this.name=name1; } public void run() { int x=this.name.length(); String m=""; for(int i=0;i<x;i++) { if(this.name.charAt(i)>='a' && this.name.charAt(i)<='z') m=m+(char)(this.name.charAt(i)-32); else m=m+(char)(this.name.charAt(i)); } boolean b1=nextDBoolean();//这里产生一个随机布尔,来判定是用第一个写线程或者第二个写线程 if (b1=true) { WriteThread1 wt1= new WriteThread(m); Thread t01= new Thread(wt1); t01.start(); t01.join(); } else { WriteThread2 wt2= new WriteThread(m); Thread t02= new Thread(wt2); t02.start(); t02.join(); } } } public class WriteThread1 implements Runnable//第一个写线程 { private string name; public WriteThread1(string name1) { this.name=name1; } public void run() { //code to send this.name somewhere else } } public class WriteThread2 implements Runnable//第二个写线程,一模一样 { private string name; public WriteThread2(string name1) { this.name=name1; } public void run() { //code to send this.name somewhere else } } public class TestRunnable//主程式 { public static void main(String[] args) { //initialize 5 thread, for example ReadThread rt1= new ReadThread("abcde"); ReadThread rt2 new ReadThread("defgh"); ReadThread rt3 new ReadThread("a34cd"); ReadThread rt4= new ReadThread("ABcDE"); ReadThread rt5= new ReadThread("lzxC8"); Thread t1= new Thread(rt1); Thread t2= new Thread(rt2); Thread t3= new Thread(rt3); Thread t4= new Thread(rt4); Thread t5= new Thread(rt5); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
[ 本帖最后由 hys1986 于 2011-5-23 07:53 编辑 ]