Java 子线程同步在此不起作用
Java代码:Java 子线程同步在此不起作用,java,Java,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);
// 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()方法,并可以在run()方法中初始化同步块(将justCall()方法的代码放入同步块)
如何在此处同步子代码?请帮忙。我读到Thread.sleep()方法在同步块或方法中执行时从不释放锁。但在我的代码中,主线程和子代码同时执行。请使用Thread.sleep()方法帮助同步子代码。当两个线程在同一对象上同步时,它们不会同时运行同一代码。这允许多个不同的线程同时在多个不同的代码区域中协作运行 非静态方法上的
synchronized
会在此
对象上创建锁。如果它是一个静态方法,那么锁就会位于NewThread
类的Class
对象上。任何类和任何类的任何实例上都可以有一个同步的
,从而创建一个锁
您只有一个线程在同步区域中运行。因此,当它被锁定时,没有其他线程试图运行锁定的代码。没有其他线程试图在NewThread
类的nt
实例上进行同步
您可能希望尝试这样做:
NewThread nt1 = new NewThread(); // create a new thread
NewThread nt2 = new NewThread(); // create a 2nd new thread
然后在主类中停止循环