首页 > 解决方案 > 无法执行同步线程

问题描述

我尝试了教科书中关于同步线程的代码。尝试按原样编写代码。但得到错误:

cannot find symbol f.start(); and t.display();

教科书代码应该在没有同步关键字的情况下尝试。但似乎编译器无法识别该对象。请帮忙..

class First 
{
    synchronized void display (String s)
    {
        System.out.println(s);

        try
        {
            Thread.sleep(1000);
        }
        catch(InterruptedException e)
        {
            System.out.println("Interrupted");  
        }
        System.out.println("***");
    }
}

class Second  implements Runnable 
{
    String s;
    First f;    
    Thread t;

    public Second(First f1,String s1)
    {
        f=f1;
        s=s1;
        t=new Thread(this);
        f.start();
    }

    public void run()
    {
        t.display(s);
    }
}

class SyncThread
{
    public static void main(String args[])
    {
        First f=new First();
        Second ob1=new Second(f,"First");
        Second ob2=new Second(f,"Second");
        Second ob3=new Second(f,"Third");

        try
        {
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        }
        catch(InterruptedException e)
        {
            System.out.println("Interrupted");
        }
    }
}

标签: javajava-threads

解决方案


而不是做

t = new Thread(this);
f.start();

尝试:

t = new Thread(this);
t.start();

并在run方法中,尝试f.display()代替t.display()

看起来你搞砸了一些变量。尝试使用一些有意义的名称而不是fand tthread.start()搞砸andfirst.display()t.start()and更难f.display()


推荐阅读