当前位置:文档之家› Java SE实验报告1

Java SE实验报告1


synchronized void print(String str) { System.out.print("[" + str); try { Thread.sleep(1000); } catch (InterruptedException e) { e.getStackTrace(); }
}} class Caller implements Runnable {
实验结果:
1. 建立的线程的内容输出不一致:
2. 修改后:
实验体会
实验一:多线程同步
班级:姓名:学号:来自实验目的:通过线程的创建、启动和多线程的同步,掌握线程的使用和多线程之间
的数据共享和传递。
实验内容:
创建线程;启动线程;线程操作;多线程同步操作。
实验步骤:
1. 实验步骤 01. 参考资料完成线程的创建、启动 02. 实现多线程的同步 03. 完成多线程之间的数据共享和传递 04. 综合实验代码、输出运行结果
/*
* 延时 1 秒后,先输出[main],然后输出启动主线程 否 则,先输出启动主线程,然后输出[main] 延时和不延时的结果不一样
*/ Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("[" + Thread.currentThread().getName() + "]"); System.out.println("--------------------------------"); Share share = new Share(); Caller call1 = new Caller(share, "A"); Thread t1 = new Thread(call1); t1.start(); Caller call2 = new Caller(share, "B"); Thread t2 = new Thread(call2); t2.start(); Caller call3 = new Caller(share, "C"); Thread t3 = new Thread(call3); t3.start(); } }
String str; Share share; Thread thread; public Caller(Share share, String str) {
this.share = share; this.str = str; } public void run() { share.print(str); System.out.println("]"); System.out.println("启动主线程:" + Thread.currentThread().getName()); System.out.println("主线程ID:" + Thread.currentThread().getId()); System.out.println("主线程优先级:" + Thread.currentThread().getPriority()); System.out.println("主线程HashCode:" + Thread.currentThread().hashCode()); }} public class ThreadSynchronized { public static void main(String[] args) { MainThread mt = new MainThread(); // 将实现Runnable的类的实例传入构造函数 Thread thread = new Thread(mt); thread.start(); // 获取主线程的名字 try {
2. 实验源代码 package Thread; /** * 多线程同步 * @author SiRuYan */ class MainThread implements Runnable {
// 重写run方法 public void run() {
// 获取当前线程的名字 System.out.println("启动主线程:" + Thread.currentThread().getName()); System.out.println("主线程ID:" + Thread.currentThread().getId()); System.out.println("主线程优先级:" + Thread.currentThread().getPriority()); System.out.println("主线程HashCode:" + Thread.currentThread().hashCode()); }} class Share {
相关主题