四个线程t1,t2,t3,t4,分别打印文字,t1只能打印1,t2只能打印2,t3只能打印3,t4只能打印4,打印如下A B C D内容: A:123412341234 B:234123412341

package t1t2t3t4;

/**
 * Created by Administrator on 2017/5/13.
 */
public class Main {
    public static void main(String[] args) {
        Object lock = new Object();
        for(int i=1;i<=4;i++){
           char str=(char) (64+i);
           System.out.print(str+":");
           NumberThread n = new NumberThread();
           n.state=i;
           Thread t1 = new Thread(n);
            t1.setName("线程1");
            Thread t2 = new Thread(n);
            t2.setName("线程2");
            Thread t3 = new Thread(n);
            t3.setName("线程3");
            Thread t4 = new Thread(n);
            t4.setName("线程4");
            t1.start();t2.start();t3.start();t4.start();
            try {
            Thread.sleep(500);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
            System.out.println();
        }
        
    }
}
package t1t2t3t4;

/**
 * Created by Administrator on 2017/5/13.
 */
public class NumberThread implements Runnable {
    int count = 0;
    int state = 1; //记录当前要执行的线程

    
    public void run() {
        while (true) {
            //传对象,通过锁这个对象,判断资源的锁定状态
            synchronized (this) {
                //如果线程名中包含state,表示线程名正确,打印数字
                if (Thread.currentThread().getName().contains(state + "")) {
                    System.out.print(state);
                    //正确线程打印一次后,增加state,用于下次正确的线程打印
                    count++;
                    state++;
                }else{
                    //要运行的线程和state不一致,则休眠, 等待下次唤醒
                    try {
                        wait();
                    } catch (InterruptedException e) {

                    }
                }
                //state加到4,从1开始
                if (state == 5) {
                    state = 1;
                   //通知其他所有线程运行。不知道运行的是哪个线程
                }
                //唤醒所有线程
                notifyAll();
                if (count == 12) {                 
                    break;
                }
            }
        }
    }
}

运行结果:

A:123412341234
B:234123412341
C:341234123412
D:412341234123

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值