题目(记不太清了):使用创建Thread的两种方法创建俩个线程,A和B,其中A打印10次张三,B打印十次李四,要求如下:
A:两个线程同时执行;
B:交替打印10次。
我的理解:我认为题目是要求用extends Thread类和implements Runnable接口分别实现A和B,然后A和B两个线程交替打印,并且每个线程打印10次自己的内容后,另一个线程开始打印。(PS:笔试的时候题目都没看清,再加上线程的东东用的少,写得也少,回来在Eclipse上实现才发现自己笔试的时候写的有多烂,哎,还是要培养纸上写代码啊。。。。。)
不多说,我的代码如下
public class TestPrintThread {
private static Lock lock = new ReentrantLock();
public static Condition a = lock.newCondition();
public static Condition b = lock.newCondition();
public static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ThreadA A = new ThreadA("张三");
ThreadB B = new ThreadB("李四");
Thread thread = new Thread(B);
A.start();
thread.start();
}
public static class ThreadA extends Thread{
private int i = 0;
public static int num = 10;
private String str;
public ThreadA(String str){
this.str = str;
}
@Override
public void run() {
num = 10;
while(i<10)
{
try{
lock.lock();
i++;
int j=0;
while(flag){
b.await();
}
while(j<10){
System.out.print(str+" ");
j++;
num--;
}
System.out.println();
flag = true;
a.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}
public static class ThreadB implements Runnable{
private int i = 0;
public static int num = 0;
private String str;
public ThreadB(String str){
this.str = str;
}
@Override
public void run() {
num = 0;
while(i<10)
{
try{
lock.lock();
i++;
int j=0;
while(!flag){
// System.out.print(str+" ");
a.await();
}
while(j<10){
System.out.print(str+" ");
num++;
j++;
}
System.out.println();
flag = false;
b.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}
}
方法二:synchronized同步代码块
public class TestPrintThread2 {
public static String flag = "flag";
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadA A = new ThreadA("zhangsan ");
Runnable r = new ThreadB("lisi ");
Thread B = new Thread(r);
A.start();
B.start();
}
public static class ThreadA extends Thread{
private String str;
public ThreadA(String str){
this.str = str;
}
public void run(){
int j = 0;
while(j<20) {
synchronized (flag){
try {
flag.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
print();
flag.notify();
j++;
}
}
}
private void print(){
int i = 0;
while(i<10){
System.out.print(str);
i++;
}
System.out.println();
}
}
public static class ThreadB implements Runnable{
private String str;
public ThreadB(String str){
this.str = str;
}
public void run(){
int j = 0;
while(j<20) {
synchronized (flag){
flag.notify();
print();
try {
flag.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
j++;
}
}
}
private void print(){
int i = 0;
while(i<10){
System.out.print(str);
i++;
}
System.out.println();
}
}
}