Java线程编程实验
一 实验内容
1、编写程序创建5个线程,分别显示5个不同的字符串,用继承Thread类以及实现Runnable接口的两种方式实现。
2、编写一个演示死锁的程序。
3、模拟多个线程并发访问堆栈状态,显示各个状态情况。
二 实验目的
(1)理解多线程的概念
(2)掌握线程的创建方法和任务类
(3)掌握事件分发线程机制
(4)理解线程池的概念及应用
(5)理解线程的同步和异步
三 实验过程
(1)问题分析
1、分别创建3个继承与Thread的类的线程和2个继承与Runnab的线程然后分别命名为线程1-5,然后输出自己的线程名。
2.创建2个线程,线程1拿到r1锁,沉睡3秒再拿到r2锁,然后输出一句话,线程2拿到r2锁,沉睡3秒再拿到r1锁,然后输出一句话。
3.创建10个线程,分别start,每个线程run方法进行栈的进入,并使top++,输出该线程存入的数字,最后输出整个栈。
(2)代码编写
//1.
public class Main{
public static void main(String args[])
{
Text t=new Text("线程1");
t.start();
Text2 tt=new Text2();
Thread t2=new Thread(tt,"线程2");
t2.start();
Thread t3=new Thread(tt,"线程3");
t3.start();
Text t4=new Text("线程4");
t4.start();
Text t5=new Text("线程5");
t5.start();
}
}
class Text extends Thread{
public String name;
Text(String name){
this.name=name;
}
public void run() {
try {
System.out.println(name);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
class Text2 implements Runnable{
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName());
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
//2.
public class Main{
public static Integer r1=1;
public static Integer r2=2;
public static void main(String args[])
{
Thread1 t1=new Thread1();
t1.start();
Thread2 t2=new Thread2();
t2.start();
System.out.println("开始");
}
}
class Thread1 extends Thread{
public void run() {
synchronized(Main.r1)
{
try {
Thread.sleep(3000);
}catch(Exception ex)
{
ex.printStackTrace();
}
synchronized(Main.r2)
{
System.out.println("running 1");
}
}
}
}
class Thread2 extends Thread{
public void run() {
synchronized(Main.r2)
{
try {
Thread.sleep(3000);
}catch(Exception ex)
{
ex.printStackTrace();
}
synchronized(Main.r1)
{
System.out.println("running 2");
}
}
}
}
//3.
public class Main{
public static volatile int top=0;
public static final int size=10;
public static volatile int numbers[]=new int[size];
public static void main(String args[]) throws InterruptedException
{
for(int i=0;i<size;i++)
{
Thread1 t1=new Thread1("线程"+i);
new Thread(t1).start();
}
try{
Thread.sleep(3000);
for(int i:numbers)
System.out.println(i);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
class Thread1 implements Runnable{
Main m=new Main();
public String name;
Thread1(String name)
{
this.name=name;
}
@Override
public synchronized void run() {
Random random=new Random();
int number=random.nextInt(10);
try{
if(m.top==m.size)
{
System.out.println("栈已经满");
}
else {
m.numbers[m.top]=number;
m.top++;
System.out.println(name+" 将数字number= "+number+"已经放入栈");
}
Thread.sleep(1000);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
运行结果截图:
1.
2.