1. 程式人生 > 其它 >兩個執行緒交替列印奇偶數

兩個執行緒交替列印奇偶數

public class Thtest {
    private static final Object obj = new Object();
    public static void main(String[] args) {

        new Thread(new Runnable(){

            @Override
            public void run() {
                for(int i = 0;i<100;i++){
                    synchronized (obj){
                        
if ((i & 1) == 1){ System.out.println(Thread.currentThread().getName()+":"+i); } obj.notify(); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } },
"奇數執行緒").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 100; i++){ synchronized (obj){ if ((i&1)==0){ System.out.println(Thread.currentThread().getName()
+":"+i); } obj.notify(); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } },"偶數執行緒").start(); } }