多线程:
Runnable的使用:
publicclass RunnableTest implements Runnable{
publicvoid run(){
System.out.println("我是任务");
}
}
publicclass TestMain2 {
publicstaticvoid main(String[] args) {
RunnableTest rt=new RunnableTest();
rt.run();
System.out.println("我是任务2");
}
}
控制台输出:
我是任务
我是任务2
Thread的使用:
publicclass ThreachTest extends Thread {
publicvoid run(){
System.out.println("打印一句话");
}
}
publicclass TestMain {
publicstaticvoid main(String[] args) {
ThreachTest th=new ThreachTest();
th.start();
System.out.println("打印一句话2");
}
}
控制台输出:
打印一句话2
打印一句话
同步锁的使用:
publicclass Admin {
private String name;
privatedoublescore;
private ReentrantLock lock=new ReentrantLock(true);
public Admin(String name, double score) {
this.name = name;
this.score = score;
}
publicvoid setScore(double score) {
this.score = score;
}
publicdouble getScore() {
returnscore;
}
publicvoid setName(String name) {
this.name = name;
}
public String getName() {
returnname;
}
publicvoid check() {
// 用synchronized锁住
synchronized(this){
System.out.println("开始阅卷");
try {
System.out.println("开始加分");
this.score=this.score+5;
System.out.println("执行了加5操作");
Thread.sleep(2000);
if(this.score==60){
System.out.println("======你及格了======");
}
if(this.score==80){
System.out.println("------你的成绩是良好------");
}
if(this.score==90){
System.out.println("******你的成绩很优秀******");
}
if(this.score==100){
System.out.println("GOOD!!!YOU ARE THE BEST");
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
// 用lock锁住
{
System.out.println("开始阅卷");
try {
lock.lock();
System.out.println("开始加分");
this.score=this.score+5;
System.out.println("执行了加5操作");
Thread.sleep(2000);
if(this.score==60){
System.out.println("======你及格了======");
}
if(this.score==80){
System.out.println("------你的成绩是良好------");
}
if(this.score==90){
System.out.println("******你的成绩很优秀******");
}
if(this.score==100){
System.out.println("GOOD!!!YOU ARE THE BEST");
}
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
publicvoid test() {
System.out.println("开始考试");
System.out.println("结束考试");
}
}
学生测试类
publicclass StudentTest implements Runnable {
/**
* 开始考试
*/
private Admin admin;
public Admin getAdmin() {
returnadmin;
}
publicvoid setAdmin(Admin admin) {
this.admin = admin;
}
publicStudentTest(){
}
public StudentTest(Admin admin){
this.admin=admin;
}
publicvoid run(){
for(int j=0;j<1;j++){
admin.test();
}
}
}
老师测试类
publicclass TeacherTest implements Runnable {
/**
* 阅卷开始
*/
private Admin admin;
public TeacherTest(Admin admin){
this.admin=admin;
}
publicvoid run(){
for(int i=0;i<14;i++){
admin.check();
}
}
}
测试类
publicclass TestMain {
/**
* 并发包
* @paramargs
*/
publicstaticvoid main(String[] args){
test();
}
publicstaticvoid test(){
Adminadmin=new Admin("小明",30);
StudentTeststu=new StudentTest();
stu.setAdmin(admin);
TeacherTesttea=new TeacherTest(admin);
ExecutorServiceexec=Executors.newCachedThreadPool();
exec.execute(stu);
exec.execute(tea);
exec.shutdown();
}
}