スレッドは順番に数字を印刷します。
タイトル:3つのスレッドを起動して、自己増加数を印刷して、1から45まで印刷して、スレッドごとに5つの数字を順次印刷します。
まず二つの偽の実現を見ます。
1.
まず二つの偽の実現を見ます。
1.
public class test1 implements Runnable
{
public static int num=1;
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+": "+num++);
}
}
public static void main(String[] args) throws Exception{
for(int i=0;i<3;i++) {
Thread test1 = new Thread(new Main(), "thread1");
test1.start();
test1.join();
Thread test2 = new Thread(new Main(), "thread2");
test2.start();
test2.join();
Thread test3 = new Thread(new Main(), "thread3");
test3.start();
test3.join();
}
}
}
, 3*3 ;
2
, , Thread , , run() 。
public class test2{
String name;
public test3(String name) {
this.name=name;
}
public static int num = 1;
public void run() {
for (int i = 0; i <5; i++) {
System.out.println(name + ": " + num++);
}
}
public static void main(String[] args) {
test3 t1 = new test3("thread1");
test3 t2 = new test3("thread2");
test3 t3 = new test3("thread3");
for(int i=0;i<3;i++){
t1.run();
t2.run();
t3.run();
}
}
}
。
3.
, , 。
: synchronized , - , 5 , , , ? , notify notifyAll:
(1)notify , —— ; , 。
, , while 45 , 1 5 , , , 2 , , 1 ,…… , https://blog.csdn.net/c______________/article/details/78655374,
, 。
(2)notifyAll , , , state, , , , 。
class run implements Runnable {
private int count=0;
@Override
public void run() {
while(count<3){// , 5
count++;
new Main().printNum(Thread.currentThread().getName());
}
}
}
public class Main {
public static int num=1;
public static int state=1;
public void printNum(String tag) {
synchronized (Main.class) {
int intTag = Integer.parseInt(tag);
while (intTag != state) {
try {
Main.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + num++);
}
state = state % 3+1; //state=(state+1)%3
Main.class.notifyAll();
}
}
public static void main(String[] args){
new Thread(new run(),1+"").start();
new Thread(new run(),2+"").start();
new Thread(new run(),3+"").start();
}
}
・