No.1编写一个打印机类
写两个方法
public class Printer { public void print1()
{ System.out.print("微");
System.out.print("冷");
System.out.print("的");
System.out.print("雨");
System.out.println();
}
public void print2()
{ System.out.print("好");
System.out.print("人");
System.out.println(); }
}
目的:为了使两个线程执行该类中的两个方法
线程一:
public class MyThread extends Thread {
public static Printer p1;
@Override
public void run() {
for (int i = 1; i <=500; i++) {
p1.print1();
}
}
线程二:
public class MyThread2 implements Runnable{
public static Printer p2;
@Override
public void run() {
for (int i = 1; i <=500; i++) {
p2.print2();
}
} }
Test类中的方法调用
public class Test {
public static void main(String[] args) {
Printer p=new Printer();
MyThread t1=new MyThread();
t1.p1=p;
t1.start();
MyThread2 t2=new MyThread2();
t2.p2=p;
Thread t3=new Thread(t2);
t3.start(); }
}
则会出现以下情况:因为程序员不能手动干预cpu分配线程资源
解决方法:加上同步锁,使当一个线程执行完之后另一个线程才有执行的权利
public class Printer { public void print1()
{
synchronized (this) {
System.out.print("微");
System.out.print("冷");
System.out.print("的");
System.out.print("雨");
System.out.println();
} }
public void print2()
{
synchronized (this) {
System.out.print("好");
System.out.print("人");
System.out.println();
} }
}
解决完毕!!!!!!!!!