Java 多线程编程实战:匿名Runnable、继承Thread、自定义异常
题目1:使用匿名Runnable实现线程计算
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int sum = 0;
for (int i = 1; i <= 500; i++) {
sum += i;
}
System.out.println('1--500所有数字的累加和为:' + sum);
}
});
thread.start();
}
}
题目2:继承Thread类实现定时打印
public class MyThread extends Thread {
@Override
public void run() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 1; i <= 10; i++) {
System.out.println(dateFormat.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
题目3:使用自定义异常实现用户登陆
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
login("admin", "123");
} catch (LoginException e) {
e.printStackTrace();
}
}
public static void login(String username, String password) throws LoginException {
if (!"admin".equals(username)) {
throw new LoginException("用户名不存在");
}
if (!"admin".equals(password)) {
throw new LoginException("密码错误");
}
System.out.println("欢迎" + username);
}
}
以上代码示例展示了在Java中使用匿名Runnable、继承Thread类和自定义异常来实现多线程编程的常见场景,你可以根据实际需要进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/od0S 著作权归作者所有。请勿转载和采集!