关于创建线程的问题 创建两个并发线程,一个是读线程,另一个是写线程。这两个线程共享一个数组A,写线程对数组分别进行10次写操作,每次写操作对A的每个元素赋一个相同的值;读线程对数组分别进行10次读操作,每次读操作输出A中所有元素的值。修改代码,使每次读写互斥,即每次对数组的写操作结束后才能进行写操作,反之亦然。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 int i[]=new int[10];void write(int w){ synchronized(i){ int j=9; while(j-->=0){ a[j]=w; } }}------------------------------int i[]=new int[10];synchronized void write(int w){ int j=9; while(j-->=0){ a[j]=w; } } class MyThread{ public static void main(String [] args) { PutGet t = new PutGet(); new Thread(new Product(t)).start(); new Thread(new Consumer(t)).start();}}class PutGet{ private String name; private String sex; boolean b=false; public void put(String name,String sex) { if(b) try{wait();}catch(Exception e){} this.name=name; this.sex=sex; b=true; try{notify();}catch(Exception e){} } public void get() { if(!b) try{wait();}catch(Exception e){} System.out.println(name+"-----"+sex); b=false; try{notify();}catch(Exception e){} }}class Product implements Runnable{ PutGet q=null; int i=0; public Product(PutGet q) { this.q=q; } public void run() { while(true) { synchronized(q) { if(i==0) { q.put("利","男"); i=(i+1)%2; } else { q.put("静","女"); i=(i+1)%2; } } } } }class Consumer implements Runnable{ PutGet q=null; public Consumer(PutGet q) { this.q=q; } public void run() { while(true) { synchronized(q) { q.get(); } } }} 初时运行是,读线程等待(wait),写线程工作,工作完毕,notify,然后wait写线程被唤醒后工作,工作完毕,notify,然后wait就这样。 htmlparser,怎样提取tbody? 页面显示问题 哪位大哥可以帮我看看 一个简单java题,帮忙解决一下 正则表达式的问题 TimedOutException 不是一个RuntimeException??什么是RuntimeException???? Java中怎样迅速比较两个文本文件是否完全一致? 学习struts2.X的疑惑 ">>>"是什么意思 各位大虾,小弟很想学JAVA,可是始终没找到一本带有JDK1.3并且很优秀的书,能推荐一本吗?谢谢! help me:关于Jdbc的问题!!! 怎么让队列里头的数据被更新时得到通知?! FileFilter Filenamefilter
void write(int w){
synchronized(i){
int j=9;
while(j-->=0){
a[j]=w;
}
}
}
------------------------------
int i[]=new int[10];
synchronized void write(int w){
int j=9;
while(j-->=0){
a[j]=w;
}
}
{
public static void main(String [] args)
{
PutGet t = new PutGet();
new Thread(new Product(t)).start();
new Thread(new Consumer(t)).start();
}
}
class PutGet
{
private String name;
private String sex;
boolean b=false;
public void put(String name,String sex)
{
if(b)
try{wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
b=true;
try{notify();}catch(Exception e){}
}
public void get()
{
if(!b)
try{wait();}catch(Exception e){}
System.out.println(name+"-----"+sex);
b=false;
try{notify();}catch(Exception e){}
}
}
class Product implements Runnable
{
PutGet q=null;
int i=0;
public Product(PutGet q)
{
this.q=q;
}
public void run()
{
while(true)
{
synchronized(q)
{
if(i==0)
{
q.put("利","男");
i=(i+1)%2;
}
else
{
q.put("静","女");
i=(i+1)%2;
}
}
}
}
}
class Consumer implements Runnable
{
PutGet q=null;
public Consumer(PutGet q)
{
this.q=q;
}
public void run()
{
while(true)
{
synchronized(q)
{
q.get();
}
}
}
}
写线程被唤醒后工作,工作完毕,notify,然后wait
就这样。