可以在JAVA中的同一个同步方法中一起存在wait()和notify(),并且一个线程进入synchronized方法并等待其他方法进入相同的synchronized方法并且notifyall?我需要顺序打印线程名称。使用等待和通知,我试图使用下面的代码。 以下是输出响应:
等待线程5 线程主出口 等待线程2 等待线程3 等待线程4 线程开始1 等待线程1
public class Printthread实现了Runnable {
Thread t ;
static int number = 1;
boolean check = true;
public Printthread(String name)
{
t = new Thread(this,name);
t.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
print();
System.out.println(" thread EXIT " + t.getName());
}
synchronized public void print()
{
while(Integer.parseInt(t.getName()) != number)
{
try {
System.out.println(" Waiting thread " + t.getName());
wait();
System.out.println(" resumed thread started " + t.getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(Integer.parseInt(t.getName()) == number)
{
System.out.println(" thread started " + t.getName());
number = number + 1;
notifyAll();
}
}
}
公共类ThreadMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub\
Printthread p5 = new Printthread("5");
Printthread p2 = new Printthread("2");
Printthread p4 = new Printthread("4");
Printthread p3 = new Printthread("3");
Printthread p1 = new Printthread("1");
System.out.println("Thread main exit");
}
}
答案 0 :(得分:-1)
你的逻辑错了。同步块不在同一个对象上,因为您正在创建5个不同的Printthread
对象。对于您的问题,是的,它们可以存在于同一个同步块中。这是正确的版本:
public class PrintThread implements Runnable {
static int number = 1;
public PrintThread() {
Thread t1 = new Thread(this, "1");
Thread t2 = new Thread(this, "2");
Thread t3 = new Thread(this, "3");
Thread t4 = new Thread(this, "4");
Thread t5 = new Thread(this, "5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
print();
System.out.println(" thread EXIT " + Thread.currentThread().getName());
}
synchronized static int getNumber() {
return number;
}
synchronized static void incNumber() {
number++;
}
synchronized public void print() {
while (Integer.parseInt(Thread.currentThread().getName()) != number) {
try {
System.out.println(" Waiting thread " + Thread.currentThread().getName());
wait();
System.out.println(" resumed thread started " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (Integer.parseInt(Thread.currentThread().getName()) == number) {
System.out.println(" thread started " + Thread.currentThread().getName());
incNumber();
notifyAll();
}
}
public static void main(String[] args) {
new PrintThread();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread main exit");
}
}