大家看看下面的代码哪里有问题,为什么用javac编译的时候出现了乱码。貌似图片只能以附件形式加进来。图片见附件。
- import java.util.concurrent.locks.*;
- class Demo{
- public static void main(String[] args){
- Res r = new Res();
- new Thread(new Pro(r)).start();
- new Thread(new Pro(r)).start();
- new Thread(new Con(r)).start();
- new Thread(new Con(r)).start();
- }
- }
- class Res{
- private String name;
- private int count = 1;
- private boolean flag = false;
- final Lock lock = new ReentrantLock();
- final Condition condition_pro = lock.newCondition();
- final Condition condition_con = lock.newCondition();
- public void set(){
- lock.lock();
- try{
- while(flag)
- condition_pro.await();
-
- this.name = "Producer......"+ count++;
- System.out.println(this.name);
- flag = true;
- condition_con.signal();
- }
- catch(InterruptedException e){
- System.out.println(e.toString());
- }
- finally{
- lock.unlock();
- }
- }
- public void out(){
- lock.lock();
- try{
- while(!flag)
- condition_con.await();
-
- System.out.println(name);
- flag = false;
- condition_pro.signal();
- }
- catch(InterruptedException e){
- System.out.println(e.toString());
- }
- finally{
- lock.unlock();
- }
- }
- }
- class Pro implements Runnable{
- private Res r = null;
- Pro(Res r){
- this.r = r;
- }
- public void run(){
- for(int x = 0;x<80; x++)
- r.set();
- }
- }
- class Con implements Runnable{
- private Res r = null;
- Con(Res r){
- this.r = r;
- }
- public void run(){
- for(int x = 0;x<80; x++)
- r.out();
- }
- }
复制代码
|
|