论坛首页 Java企业应用论坛

三个线程循环打印abc十次

浏览 19672 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2011-12-28  
public class ThreadPrintABC {

	private static final int THREAD_NUM = 3;

	private static final Integer mutex = 0;

	private static int globalIndex = 0;


	public static void main(String[] args) {
		WorkThread a = new WorkThread("A", 0);
		WorkThread b = new WorkThread("B", 1);
		WorkThread c = new WorkThread("C", 2);
		a.start();
		b.start();
		c.start();
	}

	private static class WorkThread  extends Thread{

		private int index ;

		private String name;

		WorkThread(String name, int index) {
			this.index = index;
			this.name = name;
		}

		@Override
		public void run() {

			while (true) {
				synchronized (mutex) {
					if (this.index == globalIndex){
						System.out.print(name);
						globalIndex = (globalIndex + 1) % THREAD_NUM;
						mutex.notifyAll();
					}else {
						try {
							mutex.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();

						}
					}
				}
			}

		}
	}
0 请登录后投票
   发表时间:2011-12-28  
public class Test {
ReentrantLock lock = new ReentrantLock();
Condition conda = lock.newCondition();
Condition condb = lock.newCondition();
Condition condc = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
new Test().method();
}
public void method() throws InterruptedException {
new MyThread(conda, condb, lock, "A").start();
new MyThread(condb, condc, lock, "B").start();
new MyThread(condc, conda, lock, "C").start();
}
}
class MyThread extends Thread {
Condition condOwn;
Condition condNext;
ReentrantLock lock;
String name;
int SIZE = 10;
public MyThread(Condition condOwn, Condition condNext, ReentrantLock lock, String name) {
super();
this.condOwn = condOwn;
this.condNext = condNext;
this.lock = lock;
this.name = name;
}
public void run() {
for (int i = 1; i <= 10; i++) {
lock.lock();
try {
System.out.print(name);
if (i == SIZE) {
condNext.signal();
} else {
condNext.signal();
condOwn.await();
}
} catch (Exception e) {
} finally {
lock.unlock();
}
}
};
}



刚写的一个,应该是可以的,亲测过。
0 请登录后投票
   发表时间:2011-12-28  
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
	ReentrantLock lock = new ReentrantLock();
	Condition conda = lock.newCondition();
	Condition condb = lock.newCondition();
	Condition condc = lock.newCondition();

	public static void main(String[] args) throws InterruptedException {
		new Test().method();
	}

	public void method() throws InterruptedException {
		new MyThread(conda, condb, lock, "A").start();
		new MyThread(condb, condc, lock, "B").start();
		new MyThread(condc, conda, lock, "C").start();
	}
}
class MyThread extends Thread {
	Condition condOwn;
	Condition condNext;
	ReentrantLock lock;
	String name;
	int SIZE = 10;

	public MyThread(Condition condOwn, Condition condNext, ReentrantLock lock,
			String name) {
		super();
		this.condOwn = condOwn;
		this.condNext = condNext;
		this.lock = lock;
		this.name = name;
	}

	public void run() {
		for (int i = 1; i <= 10; i++) {
			lock.lock();
			try {
				System.out.print(name);
				if (i == SIZE) {
					condNext.signal();
				} else {
					condNext.signal();
					condOwn.await();
				}
			} catch (Exception e) {
			} finally {
				lock.unlock();
			}
		}
	};
}

重新编辑了下。
0 请登录后投票
   发表时间:2011-12-28  
public static void main(String[] args)
{
 
	MyThread A = new MyThread("A");
	MyThread B = new MyThread("B");
	MyThread C = new MyThread("C");
	A.setNext(B);
	B.setNext(C);
	C.setNext(A);
	A.start();
	B.start();
	C.start();
        A.doing();
}

class MyThread extends Thread
{
	private Object lock;
	private MyThread next;
	private int count=0;
	private int maxCount=10;
	
	public MyThread getNext()
	{
		return this.next;
	}
	public void setNext(MyThread next)
	{
		this.next = next;
	}
	public MyThread(String name)
	{
		this.setName(name);
		this.lock=new Object();
 	 
	}
	public void doing()
	{
		synchronized(lock)
		{
			lock.notify();
		}
	}
	@Override
	public void run()
	{
		while(count<maxCount && next!=null)
		{
			synchronized(lock)
			{
				try
				{
					
						lock.wait();
					
				} catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println(this.getName());
			count=count+1;
			next.doing();
		}
	}
}


这个可以吧。
0 请登录后投票
   发表时间:2011-12-28  

/**
* @author my_corner 2011-12-26
*/
public class ThreadPrint {
protected static int status = 0;

/**
* @author my_corner
* @param
* @return
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {

Thread a = new PrintTask1();
a.setName("a");
Thread b = new PrintTask2();
b.setName("b");
Thread c = new PrintTask3();
c.setName("c");

a.start();
b.start();
c.start();

}

}

class PrintTask1 extends Thread {
private int times = 0;

/**
*
*/
@Override
public void run() {
while (times < 30) {
if (ThreadPrint.status % 3 == 0) {
System.out.println(this.getName());
ThreadPrint.status++;
times++;
}
}
}

}

class PrintTask2 extends Thread {
private int times = 0;

/**
*
*/
@Override
public void run() {
while (times < 30) {
if (ThreadPrint.status % 3 == 1) {
System.out.println(this.getName());
ThreadPrint.status++;
times++;
}
}
}

}

class PrintTask3 extends Thread {
private int times = 0;

/**
*
*/
@Override
public void run() {
while (times < 30) {
if (ThreadPrint.status % 3 == 2) {
System.out.println(this.getName());
ThreadPrint.status++;
times++;
}
}
}

}
0 请登录后投票
   发表时间:2011-12-29  
public class TestPrint {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyLock lock = new MyLock(0);
		Thread t1 = new Thread(new MyJob(lock, "A"));
		Thread t2 = new Thread(new MyJob(lock, "B"));
		Thread t3 = new Thread(new MyJob(lock, "C"));
		t1.start();
		t2.start();
		t3.start();
	}
}

class MyLock {
	private int counter = 0;

	public MyLock(int counter) {
		this.counter = counter;
	}

	public synchronized void addCounter() {
		counter++;
	}

	public synchronized int getCurrentIndex() {
		return counter % 3;
	}
}

class MyJob implements Runnable {

	private String str;
	private MyLock lock;
	private int index = 0;
	private int times = 0;

	public MyJob(MyLock lock, String str) {
		this.lock = lock;
		this.str = str;
		if ("B".equals(str)) {
			this.index = 1;
		} else if ("C".equals(str)) {
			this.index = 2;
		}
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public Object getLock() {
		return lock;
	}

	public void setLock(MyLock lock) {
		this.lock = lock;
	}

	@Override
	public void run() {

		synchronized (lock) {
			while (times < 10) {
				if (lock.getCurrentIndex() != index) {
					try {
						lock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {

					System.out.print(str);
					if (index == 2) {
						System.out.println(",");
					}
					times++;
					lock.addCounter();
					lock.notifyAll();
				}
			}

		}

	}

}


0 请登录后投票
   发表时间:2011-12-29  
丑陋的程序
0 请登录后投票
   发表时间:2011-12-29  
yanglover 写道
我记得有一个类叫什Condition,它就是一个条件,你可以看下。应该能够很轻松地实现你要的功能。
java.util.concurent.locks里面。

你指的是ReentrantLock吧,它确实可以实现synchronized同样的效果。但它还是与互拆同步锁有着不同的,主要是有三个特点:等待可中断,实现公平锁,以及可以绑定多个条件。另外在jdk1.6版本以前,性能也是考虑ReentrantLock的一个主要原因。但jdk后来对synchronized做了很多的优化,所以性能上差别已经不大了。如果两者都可选的话,可能选择synchronized会更好些。因为后台虚拟机性能的改进会更偏向原生的synchronized。
当然,鉴于当前的题目,使用ReentrantLock也是一个不错的选择,因为字母要顺序输出,所以它可实现公平锁的特性对线程的顺序执行有很大的帮助。
0 请登录后投票
   发表时间:2011-12-29  
my_corner 写道
神之小丑 写道
public class OutThread extends Thread{  
	  
    /** 
     * @param args 
     */  
    private final static int maxCount=100;  
    private static boolean[] bool={true,false,false};  
    private int tag;  
    private int count;  
    public OutThread(String ot,int tag){  
        super(ot);  
        this.tag=tag;  
          
    }  
    public static void main(String[] args) throws InterruptedException {  
          
        Thread threadA=new OutThread("A",0);  
        Thread threadB=new OutThread("B",1);  
        Thread threadC=new OutThread("C",2);  
          
        long begin=System.currentTimeMillis();  
        threadA.start();  
  
        threadB.start();  
  
        threadC.start();  
          
        threadA.join();  
  
        threadB.join();  
  
        threadC.join();  
          
        long end=System.currentTimeMillis();  
          
        System.out.println();  
        System.out.println("耗时: "+(end-begin)+"ms");  
    }  
      
    public void run(){  
        try{  
            synchronized (bool) {  
                while(true){  
                    if(bool[this.tag]){  
                        System.out.print(Thread.currentThread().getName());  
                        this.count++;  
                        bool[this.tag]=false;  
                        bool[(this.tag+1)%3]=true;  
                        bool[(this.tag+2)%3]=false;  
                        bool.notifyAll();  
                        if(count==maxCount)  
                            return;  
                          
                    }else{  
                        bool.wait();  
                    }  
                }  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
          
    }  
  
} 

比我写的好


提点个人的小意见,如果想最后输出耗时,按现在程序处理逻辑,最后不需要逐个等待线程执行完毕,只需要执行threadC.join();即可。当然,原有的写法也不会有什么错误。我只是从精减代码的角度提的。
0 请登录后投票
   发表时间:2011-12-30  
public class ABCSortThread{

	private String[] str = new String[]{"A","B","C"};
	
	/**
	 * 数组其实位置
	 */
	Integer index = 0;
	
	/**
	 * 执行打印次数统计
	 */
	Integer exeCounts = 0;
	
	/**
	 * 最多执行次数限制
	 */
	int maxExeCounts = 10;
	
	/**
	 * 执行线程
	 * 
	 * @author yanwj06282@hundsun.com
	 *
	 */
	class Thread1 extends Thread {
		
		private String name;
		
		public Thread1(String name) {
			this.name = name;
		}
		
		public void run() {
			for (int i = 0; exeCounts < maxExeCounts; i++) {
				synchronized (ABCSortThread.class) {
					if (exeCounts < maxExeCounts && name.equals(str[index%str.length])) {
						System.out.println(name);
						index ++ ;
						exeCounts ++;
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {
		ABCSortThread abc = new ABCSortThread();
		Thread threa1 = abc.new Thread1("A");
		Thread threa2 = abc.new Thread1("B");
		Thread threa3 = abc.new Thread1("C");
		threa1.start();
		threa2.start();
		threa3.start();
	}
	
}
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics