享的资源一次只被一个线程使用。实 现此目的的过程称为“同步” 。 可以用两种方法实现同步: 同步方法:通过在方法声明中加入 synchronized 关键字可以声明要同步方法 同步块:通过 synchronized 关键字将一个
程序块声明为同步代码块 二、 编程题
1.编写一个程序,通过继承 Thread 创建线程并以此生成两个线程,每个线程输出从 1 .编写一个程序, 创建线程并以此生成两个线程, 的数。 到 5 的数。 //参考答案 1 public class XT010201 extends Thread{ public static void main(String args[]){ new XT010201(); } public XT010201(){ Thread t1=new Thread(this); t1.setName("线程 1 "); Thread t2=new Thread(this); t2.setName("线程 2 "); t1.start(); t2.start(); } public void run(){ //System.out.println(Thread.currentThread().getName()); for(int i=1;i<=100;i++){ System.out.println(Thread.currentThread().getName()+" "+i); } }
2
}
//参考答案 2 class MyThread extends Thread { public MyThread(String name) { this.setName(name); } public void run(){ for(int i=1;i<=100;i++){ System.out.println(Thread.currentThread().getName()+i); } } } public class XT010201 { public static void main(String args[]){ MyThread t1=new MyThread("线程 1 "); MyThread t2=new MyThread("线程 2 "); t1.start(); t2.start(); } } 2. . 创建一个名称为 Myapplet 的 Applet, , 通过实现 Runnable 接口为其提供多线程的功 的数字,且每个数字间延迟 毫秒。 能。在 Applet 中输出从 1 到 20 的数字,且每个数字间延迟 300 毫秒。 import java.awt.*; import jav
a.applet.*; public class XT010202 extends Applet implements Runnable{ int i; Thread t; public void init() { t=new Thread(this); t.start(); } public void run() { for(i=1;i<=20;i++){ try { repaint(); Thread.sleep(300);
3
} catch(InterruptedException e){ System.out.println(e); } } } public void paint(Graphics g){ g.drawString("i 等于"+i,30,30); } }
3.编写程序,通过多线程实现电子实钟的功能。程序的运行结果如图 10-6 所示。 .编写程序,通过多线程实现电子实钟的功能。 所示。
图 10-6 import java.awt.*; import java.util.Calendar; public class XT0102031 { public static void main(String args[]) { Label l = new Label(); Frame f=new Frame("电子时钟"); f.add(l); f.setSize(150,100); f.setVisible(true); new SetTime(l).start(); while (true) {} }//end main()
4
}//end class class SetTime extends Thread String hour,minute,second; Label l; SetTime(Label l) { this.l = l ; } public void run() { while(true) { Calendar c = Calendar.getInstance(); if (c.get(Calendar.HOUR_OF_DAY)<10) hour="0" + c.get(Calendar.HOUR_OF_DAY); else hour=""+c.get(Calendar.HOUR_OF_DAY); if (Calendar.MINUTE<10) minute="0"+c.get(Calendar.MINUTE); else minute=""+c.get(Calendar.MINUTE); if (c.get(Calendar.SECOND)<10) second="0"+c.get(Calendar.SECOND); else second=""+c.get(Calendar.SECOND); l.setText(hour+":"+minute+":"+second); try { Thread.sleep(1000); } catch (InterruptedException e){} }//end while } } 4.编写一个创建三个线程对象的程序。每个线程应该输出一则消息,并且消息后紧 .编写一个创建三个线程对象的程序。每个线程应该输出一则消息, 线程对象的程序 跟字符串“消息结束” 要求:在线程输出消息后,暂停一秒钟后才输出“消息结束” 跟字符串“消息结束” 要求:在线程输出消息后,暂停一秒钟后才输出“消息结束” 输 。 。 所示。 出结果如图 10-7 所示。 {
5
public class XT010204{ public static void main(St