多线程:用runnable接口编写一个线程
场景:ABCD四个人同时朗诵完一首诗:《静夜思》。一个人读一句诗,合作按顺序读完。package zuoye;
代码如下:
*
class ThreadDemo01 implements Runnable{
private int n=0;
private Object obj = new Object();
private String arr[]= {“床前明月光”,“疑是地上霜”,“举头望明月”,“低头思故乡”};
public void run(){
while (true) {
synchronized(obj) {
if (n<=3) {
try {Thread.sleep(100); }
catch (InterruptedException e) { e.printStackTrace();} System.out.println(Thread.currentThread().getName()+":"+arr[n]+"\n");
//为了四个线程交替朗诵的效果更明显,这里将让线程睡眠100毫秒。 n++;} else {
break;}}}}}
public class ThreadTest {
public static void main(String[] args) {
System.out.print(
“下面有请A、B、C、D同学为我们朗诵《静夜思·李白》”+"\n");
ThreadDemo01 a=new ThreadDemo01();
Thread t1=new Thread(a,“A同学”);
Thread t2=new Thread(a,“B同学”);
Thread t3=new Thread(a,“C同学”);
Thread t4=new Thread(a,“D同学”);
t3.start();
t2.start();
t1.start();
t4.start();
try {
Thread.sleep(1000); }
catch (InterruptedException e) {
e.printStackTrace();}
System.out.print(“掌声送给他们!!!”);}}*