标题: 线程交替打印问题,求大神解决下。。。 [打印本页] 作者: 格子衬衣 时间: 2015-12-9 18:14 标题: 线程交替打印问题,求大神解决下。。。 public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Resou r = new Resou("面包");
Set1 s = new Set1(r);
Get2 g = new Get2(r);
Thread t1 = new Thread(s);
Thread t2 = new Thread(g);
t1.start();
t2.start();
}
}
class Resou{
String name;
int num=0;
Resou(String name){
this.name = name;
}
public void getN(){
System.out.println("线程名为:"+Thread.currentThread().getName()+(num++)+"这是生产编号"+"生产的东西为:"+name);
}
public void setN(){
System.out.println("线程名为:"+Thread.currentThread().getName()+(num++)+"这是消费的编号"+"消费的东西为:"+name);
}
}
class Set1 implements Runnable{
Resou r ;
Set1(Resou r){
this.r = r;
}
public void run(){
while(true){
r.setN();
}
}
}
class Get2 implements Runnable{
Resou r ;
Get2(Resou r ){
this.r = r;
}
public void run(){
while(true){
r.getN();
}
}
}
到底是什么问题。我现在才开启了两个线程。。。求解。我先每个任务开启四个线程。并且用jdk5的锁机制。。。 作者: 5个半柠檬c 时间: 2015-12-9 18:14
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Resou r = new Resou("面包");
Set1 s = new Set1(r);
Get2 g = new Get2(r);
Thread t1 = new Thread(s);
Thread t2 = new Thread(s);
Thread t3 = new Thread(g);
Thread t4 = new Thread(g);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resou {
String name;
int num = 0;
boolean bool = true;
Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();