多线程:循环打印线程,例如,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();
}
}