多线程实现(代码)

多线程:循环打印线程,例如,A负责打印“A”,B负责打印“B”,循环5次,输出“ABABABABAB”

(方法一)

其中,join()方法:阻塞调用线程(join代码写在哪里,哪个就是调用线程),直到某个线程(执行join方法的线程)终止或经过了指定时间为止

public class TestABC {

     public static void main(String[] args) throws Exception {
        Thread a = new Thread(new Runner("A", 0));
        Thread b = new Thread(new Runner("B", 1));
        Thread c = new Thread(new Runner("C", 2));
        a.start();
        b.start();
        c.start();
        a.join();
        b.join();
        c.join();
    }
}
 
class Runner implements Runnable {//用Runnable接口的方式创建线程
    private String name;
    private int index;
 
    private static int g_index = 0;
    private static int g_count = 0;
 
    private static final Object lock = new Object();
 
    public Runner(String name, int index) {
        this.name = name;
        this.index = index;
        g_count++;
    }
 
    public void run() {
        for (int i = 0; i < 5; i++) {
               synchronized (lock) {
                while (g_index != index) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println(name);
                g_index = (g_index + 1) % g_count;
                lock.notifyAll();
            }
        }
    }

}

(方法二)


public class TestAB{
private Object o=new Object();
    private boolean flag=true;

class Thread1 extends Thread
{
public void run()
{
synchronized (o){
for(int i=0;i<5;i++)
   {
System.out.println("第"+(i+1)+"次");
System.out.println('A');
o.notify();
if(flag)
{
flag=false;
try{
o.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
    }
}
}
}
}
class Thread2 extends Thread
{
public void run()
{
synchronized (o){
for(int i=0;i<5;i++)
   {
System.out.println('B');
o.notify();
if(!flag)
{
flag=true;
try{
if(i!=5)
{
o.wait();}
}catch(InterruptedException e){
e.printStackTrace();
}
    }
}
}
}
}
void show()
{
new Thread1().start();
new Thread2().start();

}
public static void main(String args[])
{
TestAB t=new TestAB();
t.show();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值