java线程中的synchronized同步关键字和sleep()函数
直接po代码和截图
Student类
package com.demo.thread4;
public class Student{
public synchronized void hello1() {
System.out.println("我是同步方法hello1()******");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep(4000)结束了,我是同步方法hello1()的结尾部分........");
}
public synchronized void hello2() {
System.out.println("我是同步方法hello2()##################");
}
public void hello3() {
System.out.println("我是普通方法hello3()------------------------");
}
public void hello4() {
System.out.println("我是普通方法hello4()=======");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep(4000)结束了,我是普通方法hello4()的结尾部分!!!!!!!!!!!");
}
}
Family1类
package com.demo.thread4;
public class Family1 implements Runnable{
Student student;
public Family1(Student student) {
this.student = student;
}
@Override
public void run() {
test();
}
public void test() {
student.hello1();
}
}
Family2类
package com.demo.thread4;
public class Family2 implements Runnable{
Student student;
public Family2(Student student) {
this.student = student;
}
@Override
public void run() {
test();
}
public void test() {
student.hello2();
}
}
Family3类
package com.demo.thread4;
public class Family3 implements Runnable{
Student student;
public Family3(Student student) {
this.student = student;
}
@Override
public void run() {
test();
}
public void test() {
student.hello3();
}
}
Family4类
package com.demo.thread4;
public class Family4 implements Runnable{
Student student;
public Family4(Student student) {
this.student = student;
}
@Override
public void run() {
test();
}
public void test() {
student.hello4();
}
}
Test类
package com.demo.thread4;
public class Test {
public static void main(String[] args) {
Student student = new Student();
Family1 family1 = new Family1(student);
Family2 family2 = new Family2(student);
Family3 family3 = new Family3(student);
Thread thread1 = new Thread(family1, "线程1");
Thread thread2 = new Thread(family2, "线程2");
Thread thread3 = new Thread(family3, "线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
运行结果:可以多运行几次
运行结果,情况1
运行结果,情况2
运行结果,情况3
Test2类
package com.demo.thread4;
public class Test2 {
public static void main(String[] args) {
Student student = new Student();
Family4 family4 = new Family4(student);
Family2 family2 = new Family2(student);
Family3 family3 = new Family3(student);
Thread t1 = new Thread(family4, "线程1");
Thread t2 = new Thread(family2, "线程2");
Thread t3 = new Thread(family3, "线程3");
t1.start();
t2.start();
t3.start();
}
}
运行结果:可以多运行几次
运行结果,情况1
运行结果,情况2
标签:java,student,synchronized,void,Thread,线程,Student,new,public
来源: https://blog.csdn.net/czh500/article/details/88922133