黑马程序员技术交流社区
标题:
下面代码中的报错原因是什么?
[打印本页]
作者:
冷月霜飞
时间:
2015-6-5 06:30
标题:
下面代码中的报错原因是什么?
public class ThreadDemo2 {
public static void main (String [] args){
Tickets tic = new Tickets();
Thread t1 = new Thread(tic);
Thread t2 = new Thread(tic);
Thread t3 = new Thread(tic);
Thread t4 = new Thread(tic);
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println(Thread.currentThread().getName());
}
}
class Tickets implements Runnable{
private int tickets = 5000;
private Object obj = new Object();
public void run(){
while(true){
synchronized (obj){
if(tickets > 0){
}
try{Thread.sleep(1);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"..."+tickets--);
}
else {
return;
}
}
}
}
复制代码
在上述代码中,
else {
return;
}
复制代码
这句代码出现了语法错误,系统eclipse提醒删除该代码,但是我删除后发现,运行时处于无限循环状态,根本停不下了,但是如果加上这句代码,编译器又报语法错误,有点看不懂了,哪位师兄帮忙解决一下?谢谢了!
作者:
嘎路的米
时间:
2015-6-5 07:15
你的代码相当于如下的代码
public class Demo
{
public static void main(String[] args) throws Exception
{
Tickets tic = new Tickets();
Thread t1 = new Thread(tic);
Thread t2 = new Thread(tic);
Thread t3 = new Thread(tic);
Thread t4 = new Thread(tic);
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println(Thread.currentThread().getName());
}
}
class Tickets implements Runnable
{
private int tickets = 5000;
private Object obj = new Object();
public void run()
{
while (true)
{
synchronized (obj) {
if (tickets > 0)
{
}
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
}
System.out.println(Thread.currentThread().getName() + "..."
+ tickets--);
else
{
return ;
}
}
}
}
}
复制代码
你的else语句上缺少一个判断语句。else语句是不能单独用的,但是if语句可以单独使用
例如
if(true)
{
System.out.println("我可以单独使用");
}
复制代码
-----------------------------
if(true)
{
System.out.println("我可以单独使用");
}
else{
System.out.println("我需要结合if语句使用");
}
复制代码
--------------------------
以下的格式是错误的:
else
{
System.out.println("我需要结合if语句使用");
}
复制代码
--------------------------
还有,写代码的时候括号要写整齐一点,代码没有层次感看起来很容易混乱
作者:
2666fff
时间:
2015-6-5 07:49
。。楼上在说什么,楼主的问题很简单。。把return 换成break;
那是循环,所以直接跳出就行了
作者:
冷月霜飞
时间:
2015-6-5 08:53
嘎路的米 发表于 2015-6-5 07:15
你的代码相当于如下的代码
感谢师兄回复,问题已解决,for语句处多了半个大括号,应将try{}catch语句放到for大括号之间!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2