[Java] 纯文本查看 复制代码
public class Test5 {
public static void main(String[] args) {
MyRunnable mr =new MyRunnable();
Thread t1 = new Thread(mr,"A");
Thread t2 = new Thread(mr,"B");
Thread t3 = new Thread(mr,"C");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable{
private static int sum =1;
@Override
public void run() {
while(sum<=100){
synchronized (MyRunnable.class) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(sum ==100){
System.out.println(Thread.currentThread().getName()+"老师发了第"+sum+"份试卷,试卷分发完毕");
}else{
System.out.println(Thread.currentThread().getName()+"老师发了第"+sum+"份试卷,还剩"+(100-sum)+"份试卷");
}
sum++;
}
}
}
}
[Java] 纯文本查看 复制代码
package thread;
public class Test5 {
public static void main(String[] args) {
MyRunnable mr =new MyRunnable();
Thread t1 = new Thread(mr,"A");
Thread t2 = new Thread(mr,"B");
Thread t3 = new Thread(mr,"C");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable{
private static int sum =1;
Object obj=new Object();
@Override
public void run() {
while(true){
synchronized ( obj) {
if(sum<=100){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(sum ==100){
System.out.println(Thread.currentThread().getName()+"老师发了第"+sum+"份试卷,试卷分发完毕");
}else{
System.out.println(Thread.currentThread().getName()+"老师发了第"+sum+"份试卷,还剩"+(100-sum)+"份试卷");
}
sum++;
}
}
}
}
}