操作系统实验一_多线程

实验一 多线程
1.Thread类:

package mypackage;
import java.io.*;
import java.lang.Thread;

class MyThread1 extends Thread{
	public MyThread1(String name){
		super(name);
	}
	public void run(){
		for(int i=1;i<=10;i++){
			System.out.println(this.getName()+i);
		}
	}
}
class MyThread2 extends Thread{
	public void run(){
		for(int j=1;j<=10;j++){
			System.out.println("子线程2:"+j);
		}
	}
}
public class MyMainClass {

	//主线程
	public static void main(String[] args) {
		//子线程1
		MyThread1 mt1=new MyThread1("mychildthread1");
		//mt1.setPriority(Thread.MAX_PRIORITY);
		mt1.start();//让子线程1进入就绪状态
		//子线程2
		MyThread2 mt2=new MyThread2();
		//mt2.setPriority(Thread.MIN_PRIORITY);
		mt2.start();//让子线程2进入就绪状态
		
		for(int k=1;k<=10;k++){
			System.out.println("主线程:"+k);
		}
	}

}

2.Runnable类

import java.lang.Runnable;

class MyPrint{
	public void print(String str){
		System.out.println(str);
	}
}

class MyThread1 extends MyPrint implements Runnable{
	public void run(){
		for(int i=1;i<=10;i++){
			print("子线程1:"+i);
		}
	}
}

class MyThread2 extends MyPrint implements Runnable{
	public void run(){
		for(int i=1;i<=10;i++){
			print("子线程2:"+i);
		}
	}
}

public class MyMainClass {

	//主线程
	public static void main(String[] args) {
		//子线程1
		MyThread1 mt1=new MyThread1();
		Thread mtt1=new Thread(mt1);
		mtt1.start();
		//子线程2
		MyThread2 mt2=new MyThread2();
		Thread mtt2=new Thread(mt2);
		mtt2.start();
       		
		for(int k=1;k<=10;k++){
			System.out.println("主线程:"+k);
		}
	}

}

3.线程同步

class SynInfo {
    private String info1; 
    private String info2; 
    private int count; 
    public void modifyInfo(String info) { 
       info1 = info; 
       info2 = info; 
       if((info1.compareTo(info2))!=0) {
           System.out.println("运行第"+count +"次,信息出现不同现象!");
       } 
       count++; 
    } 
}
public class SynInfoTest {

    public static void main(String[] args) {

        final SynInfo sinfo = new SynInfo(); 

        // 假设会有两个线程可能更新SynInfo对象

        Thread thread1 = new Thread(new Runnable() { 

           public void run() { 

              while(true) 

                  sinfo.modifyInfo("infoone"); 

           } 

        }); 
        Thread thread2 = new Thread(new Runnable() { 
            public void run() { 
               while(true) 
                   sinfo.modifyInfo("infotwo");    
            } 
        });          
        System.out.println("开始测试.....");         
        thread1.start(); 
        thread2.start();
    }
} 
posted @ 2022-05-10 12:35  亚1918  阅读(39)  评论(0编辑  收藏  举报