62,621
社区成员
发帖
与我相关
我的任务
分享
synchronized(key){
if(a=='A'){
while(ThreadABC.last != 'C')
try {
key.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}else
while(ThreadABC.last != a-1)
try {
key.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(a);
ThreadABC.last = a;
key.notifyAll();
}
public class ThreadABC
{
public static char last = 'C';
public static byte[] key = new byte[0];
public static void main(String[] args)
{
new Thread(new ABC(0,key)).start();
new Thread(new ABC(1,key)).start();
new Thread(new ABC(2,key)).start();
}
}
class ABC implements Runnable
{
char a = 'A';
byte[] key;
ABC(int i,byte[] key)
{
this.key = key;
a = (char)(a + i);
}
public void run()
{
while(true){
synchronized(key){
while(ThreadABC.last!=(a-63)%3+65)
try {
key.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(a);
ThreadABC.last = a;
key.notifyAll();
}
try{
Thread.sleep(100);
}
catch(InterruptedException e)
{
}
}
}
}
class ABC implements Runnable
{
char a = 'A';
ABC(int i)
{
a = (char)(a + i);
}
public void run()
{
for(int i=0; i<10; i++)
{
System.out.println(a);
try{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class ThreadTest
{
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.execute(new ABC(0));
executorService.execute(new ABC(1));
executorService.execute(new ABC(2));
//记得运行完以后把线程都删掉,要不然程序会一直运行而不会停止
executor.shutdown();
}
}
}
import java.lang.*;
public class ThreadABC
{
public static void main(String[] args)
{
new Thread(new ABC(0)).start();
new Thread(new ABC(1)).start();
new Thread(new ABC(2)).start();
}
}
class ABC implements Runnable
{
char a = 'A';
ABC(int i)
{
a = (char)(a + i);
}
public void run()
{
for(int i=0; i<3; i++)
{
System.out.println(a);
try{
Thread.sleep(100);
}
catch(InterruptedException e)
{
}
}
}
}