网上一个有意思的题目:
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC.
以下是我的实现方式:
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC.
以下是我的实现方式:
public class Main {
public static void main(String[] args){
Data data=new Data();
new ThreadA("A",data).start();
new ThreadB("B",data).start();
new ThreadC("C",data).start();
}
}
public class ThreadA extends Thread{
private Data data;
public ThreadA(String name,Data data){
super(name);
this.data=data;
}
public void run(){
try{
for(int i=0;i<10;i++){
data.writeA();
Thread.sleep(1000);
}
}catch(InterruptedException e){
}
}
}
public class ThreadB extends Thread{
private Data data;
public ThreadB(String name,Data data){
super(name);
this.data=data;
}
public void run(){
try{
for(int i=0;i<10;i++){
data.writeB();
Thread.sleep(1000);
}
}catch(InterruptedException e){
}
}
}
public class ThreadC extends Thread{
private Data data;
public ThreadC(String name,Data data){
super(name);
this.data=data;
}
public void run(){
try{
for(int i=0;i<10;i++){
data.writeC();
Thread.sleep(1000);
}
}catch(InterruptedException e){
}
}
}
public class Data {
private DataBlock block=new DataBlock();
public void writeA()throws InterruptedException{
block.lockA();
try{
System.out.print("A");
}finally{
block.unlockA();
}
}
public void writeB()throws InterruptedException{
block.lockB();
try{
System.out.print("B");
}finally{
block.unlockB();
}
}
public void writeC()throws InterruptedException{
block.lockC();
try{
System.out.print("C");
}finally{
block.unlockC();
}
}
}
package com.thread.xunlei;
public class DataBlock {
private int flag=1;
public synchronized void lockA() throws InterruptedException{
while( flag!=1 ){
wait();
}
}
public synchronized void unlockA(){
flag=2;
notifyAll();
}
public synchronized void lockB() throws InterruptedException{
while( flag!=2 ){
wait();
}
}
public synchronized void unlockB(){
flag=3;
notifyAll();
}
public synchronized void lockC() throws InterruptedException{
while( flag!=3 ){
wait();
}
}
public synchronized void unlockC(){
flag=1;
notifyAll();
}
}