Java код:Ребенка не работает здесь
// Create a second thread.
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "Demo Thread"); // Create a new, second thread
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
public void run() // This is the entry point for the second thread.
{
justCall();
}
public synchronized void justCall()
{
try
{
for(int i = 10; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(10000);
}
}
catch (Exception e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
NewThread nt = new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
здесь вы можете удалить метод синхронизированного justCall(), и вы можете инициализировать блок синхронизации в пробеге() метод (поместить justCall (код) методы в синхронизированном блоке).
Как синхронизировать детский код здесь? Пожалуйста помоги. Я прочитал, что метод Thread.sleep() никогда не освобождает блокировку во время ее выполнения в блоке или методе синхронизации. Но в моем коде основной поток и дочерний код выполняются одновременно. Пожалуйста, помогите синхронизировать дочерний код с помощью метода Thread.sleep().