编写类ExceptionTest2: 定义两个方法:go()和main()
在go方法中声明要抛出异常,在该方法体内,抛出一个Exception对象
在main()方法中,调用go方法,使用try/catch捕获go方法中抛出的异常
class ExceptionTest2 { }
void go()throws Exception { }
throw(new Exception(\抛出的异常!\
public class Test { }
public static void main(String args[]) { }
ExceptionTest2 t2=new ExceptionTest2(); try { }
catch (Exception e) { }
e.printStackTrace(); t2.go();
实现多线程的两种方法: 继承Thread类
实现Runnable接口
先看继承Thread
class MyThread extends Thread { }
public class Test {
public static void main(String args[]) {
MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); t1.start(); t2.start(); private int ticket=5; public void run() { }
for(int i=1;i<100;i++) { }
if(ticket>0)
System.out.println(\卖票:\
}
}
t3.start();
程序运行结果如下: 卖票:5 卖票:4 卖票:3 卖票:2 卖票:5 卖票:1 卖票:5 卖票:4 卖票:4 卖票:3 卖票:2
卖票:1 卖票:3 卖票:2 卖票:1
从程序中我们可以看到3个线程各自卖各自的5张票,并没有出现共享5张票的情况。因为每一个Thread对象都有一个ticket=5.
用Runnable接口
class MyThread implements Runnable {
private int ticket=5; public void run() {
for(int i=1;i<100;i++)