高手请进——JAVA中关于线程的问题 你这个代码过不了javac. 另外也没有见线程的启动啊? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 To: helpall()只是说明一下问题的伪码,忽略语法问题。再请教 :) 线程在stare()后等待CPU空闲,一空闲就进入RUN()多线程可以用到的方法很多,具体看看书,网上很多这方面的资料 应该在class B { void check(Mydata data) { //若干操作 } } 的check()方法中加上同步: synchronized void check(Mydata data) 如果在多个Thread中需要对同一数据部分进行操作,那肯定会出现问题的。问题不一定是产生Exception,而是直接影响你的程序逻辑,可能程序会发生些莫名其妙的问题。如果要在多个Thread中对同一数据部分进行读写操作,最好在这个操作方法前加上synchronized关键字,他可以保证同时只有一个线程对该数据进行操作。如:public synchronized void setId(int i){ this.id = i;}public synchronized int getId(){ return id;} 如果你的A实例只有一个,而且触发事件的那段经常发生--产生很多线程进行B.check的查询的话就肯定出现资源竞争,会出现不确定的错误。所以建议还是采用cooled的方法,比较使用。 下面是一个线程同步问题,你好好体会一下吧!class q {//产生同步序列 int n; boolean val=false; synchronized int get(){ if(!val){ try{ wait(); }catch(java.lang.InterruptedException e){} } System.out.println("get: "+n); val=false; notify(); return n; } synchronized int put(int n){ if(val){ try{ wait(); }catch(java.lang.InterruptedException e){} } this.n=n; val=true; System.out.println("put:"+n); notify(); return n; }}class pro implements Runnable{//生产者 q q1; pro(q q1){ this.q1=q1; new Thread(this).start(); } public void run(){ int i=0; while(i!=5) try{ q1.put(i++); Thread.sleep(1000); }catch(java.lang.InterruptedException e){} }}class cust implements Runnable{//消费者 q q1; cust(q q1){ this.q1=q1; new Thread(this).start(); } public void run(){ while(true){ q1.get(); } } public static void main(String[] args) { q q1=new q(); new pro(q1); new cust(q1); }} Sun Download Manager运行报错 兔子递归问题 使用ResultSet无法打开存储过程返回的结果集 实在有点糊涂JRE,JVM,JDK这3者的关系 怎样从子线程当中得到值? 急救,mysql数据导到oracle数据库中 java怎么打包啊 ???? 为什么方法名、参数相同,返回值类型不同的方法不是重载 [菜鸟求助]各路大神,帮帮忙~急用!! 还是TextField响应的问题,把一个随机数设置为它的TEXT后,如何立刻响应。 怎么吧一个字符串写到一个文件保存下来?先谢谢啦!在线等待! 书籍选择问题,请指教!!
再请教 :)
class B
{
void check(Mydata data)
{
//若干操作
}
}
的check()方法中加上同步:
synchronized void check(Mydata data)
{
this.id = i;
}public synchronized int getId()
{
return id;
}
int n;
boolean val=false;
synchronized int get(){
if(!val){
try{
wait();
}catch(java.lang.InterruptedException e){}
} System.out.println("get: "+n);
val=false;
notify();
return n;
} synchronized int put(int n){
if(val){
try{
wait();
}catch(java.lang.InterruptedException e){}
}
this.n=n;
val=true;
System.out.println("put:"+n); notify();
return n;
}
}class pro implements Runnable{//生产者
q q1; pro(q q1){
this.q1=q1;
new Thread(this).start();
} public void run(){
int i=0;
while(i!=5)
try{
q1.put(i++);
Thread.sleep(1000);
}catch(java.lang.InterruptedException e){}
}
}
class cust implements Runnable{//消费者
q q1;
cust(q q1){
this.q1=q1;
new Thread(this).start();
} public void run(){
while(true){
q1.get();
}
}
public static void main(String[] args) {
q q1=new q();
new pro(q1);
new cust(q1);
}
}