进程:是一个正在执行中的程序。
每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元。
线程:就是进程中的一个独立的控制单元。线程在控制着进程的执行。
一个进程中至少有一个线程。
比如说:JavaVM 启动的时候会有一个进程java.exe.
该进程中至少一个线程负责java程序的执行。
而且这个线程运行的代码存在于main方法中。
该线程称之为主线程。
其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程。
自定义一个线程
通过对api的查找,java已经提供了对线程这类事物的描述。就Thread类。
该类中定义了,创建线程对象的方法(构造函数).提供了要被线程执行的代码存储的位置(run())
还定义了开启线程运行的方法(start()).
同时还有一些其他的方法用于操作线程:
staticThread currentThead():
StringgetName():
staticvoid sleep(time)throws InterruptedException:
创建线程的第一种方式:继承Thread类。
步骤:
1,定义类继承Thread。
2,复写Thread类中的run方法。
目的:将自定义代码存储在run方法。让线程运行。
3,调用线程的start方法,
该方法两个作用:启动线程,调用run方法。
class PrimeRun implements Runnable
{
long minPrime;
PrimeRun(long minPrime)
{
this.minPrime = minPrime;
}
public void run()
{ // compute primes larger than minPrime . . . } }
然后,下列代码会创建并启动一个线程:
PrimeRun p = new PrimeRun(143); new Thread(p).start();
发现运行结果每一次都不同。
因为多个线程都获取cpu的执行权。cpu执行到谁,谁就运行。
明确一点,在某一个时刻,只能有一个程序在运行。(多核除外)
cpu在做着快速的切换,以达到看上去是同时运行的效果。
我们可以形象把多线程的运行行为在互相抢夺cpu的执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,cpu说的算。
线程的状态。
1,被创建。
2,运行。
3,冻结。
4,消亡。
其实还有一种特殊的状态:临时状态。该临时状态的特点:具备了执行资格,但不具备执行权。
冻结状态的特点:放弃了执行资格。
多线程具备随机性。因为是由cpu不断的快速切换造成的。就有可能会产生多线程的安全问题。
问题的产生的原因:
1,多线程代码中有操作共享数据。
2,多条语句操作该共享数据。
当具备两个关键点时,
有一个线程对多条操作共享数据的代码执行的一部分。还没有执行完,另一个线程开始参与执行。就会发生数据错误。
解决方法:
当一个线程在执行多条操作共享数据代码时,其他线程即使获取了执行权,也不可以参与操作。
Java就对这种解决方式提供了专业的代码。
同步:
同步的原理:就是将部分操作功能数据的代码进行加锁。
同步的表现形式:
1,同步代码块。
2,同步函数。
两者不同:
同步代码块使用的锁是任意对象。
同步函数使用的锁是this。
注意:对于static的同步函数,使用的锁不是this。是 类名.class 是该类的字节码文件 对象。涉及到了单例设计模式的懒汉式。
单例设计模式。
//饿汉式。
class Single
{
privatestatic final Single s = new Single();
privateSingle(){}
publicstatic Single getInstance()
{
returns;
}
}
//懒汉式
class Single
{
privatestatic Single s = null;
privateSingle(){}
publicstatic Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s= new Single();
}
}
returns;
}
}
class SingleDemo
{
publicstatic void main(String[] args)
{
System.out.println("HelloWorld!");
}
}
如果同步函数被静态修饰后,使用的锁
通过验证,发现不在是this。因为静态方法中也不可以定义this。
静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该对象的类型是Class
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类名.class
class Ticket implements Runnable
{
privatestatic int tick = 100;
booleanflag = true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(Ticket.class)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exceptione){}
System.out.println(Thread.currentThread().getName()+"....code: "+ tick--);
}
}
}
}
else
while(true)
show();
}
publicstatic synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exceptione){}
System.out.println(Thread.currentThread().getName()+"....show....: "+ tick--);
}
}
}
class StaticMethodDemo
{
publicstatic void main(String[] args)
{
Tickett = new Ticket();
Threadt1 = new Thread(t); //线程
Threadt2 = new Thread(t);
t1.start(); //启动线程run方法
try{Thread.sleep(10);}catch(Exceptione){}
t.flag= false;
t2.start();
}
}
//例:电子时钟,通过sleep()方法改变线程的状态。代码
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.*;
public class DigitalCiock {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jf = new JFrame("Clock");
JLabel clock = new JLabel("Clock");
clock.setHorizontalAlignment(JLabel.CENTER);
jf.add(clock,"Center");
jf.setSize(140,80);
jf.setLocation(500,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
Thread t = new MyThread(clock);
t.start();
}
}
class MyThread extends Thread{
private JLabel clock;
public MyThread(JLabel clock){
this.clock = clock;
}
public void run(){
while(true){
clock.setText(this.getTime());
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public String getTime(){
Calendar c = new GregorianCalendar();
String time = c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DATE)+" ";
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
String ph = h<10 ?"0":"";
String pm = m<10 ?"0":"";
String ps = s<10 ?"0":"";
time +=ph + h + ":" + pm + m + ":" + ps + s;
return time;
}
}
//例:线程对象的生命周期从创建到结束。代码
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.*;
public class TestStatus extends WindowAdapter implements ActionListener{
Frame f;
static TestStatus.ThreadTest t1,t2;
public static void main(String[] args) {
TestStatus w=new TestStatus();
w.display();
t1=w.new ThreadTest("Welecome to Java world!");
t2=w.new ThreadTest("Welecome to Study thread!");
t2.start();
t2.setButton();
}
public void display(){
f=new Frame("welcome");
f.setSize(200,200);
f.setLocation(200,140);
f.setBackground(Color.lightGray);
f.setLayout(new GridLayout(4,1));
f.addWindowListener(this);
//f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if((e.getSource()==t1.b1)||(e.getSource()==t1.b2))
actionPerformed(e,t1);
if((e.getSource()==t2.b1)||(e.getSource()==t2.b2))
actionPerformed(e,t2);
}
public void actionPerformed(ActionEvent e,ThreadTest t){
if(e.getSource()==t.b1){
t.sleeptime=Integer.parseInt(t.tf2.getText());
t.start();
}
if(e.getSource()==t.b2)
t.interrupt();
t.setButton();
}
public class ThreadTest extends Thread{
Panel p1;
Label lb1;
TextField tf1,tf2;
Button b1,b2;
int sleeptime=(int)(Math.random()*100);
public ThreadTest(String str){
super(str);
for(int i=0;i<100;i++){
str=str+" ";
}
tf1=new TextField(str);
f.add(tf1);
p1=new Panel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
lb1=new Label("sleep");
tf2=new TextField(""+sleeptime);
p1.add(lb1);
p1.add(tf2);
b1=new Button("启动");
b2=new Button("中断");
p1.add(b1);
p1.add(b2);
b1.addActionListener(new TestStatus());
b2.addActionListener(new TestStatus());
f.add(p1);
f.setVisible(true);
}
public void run(){
String str;
//while(this.isAlive() &&!this.isInterrupted()){
while(true){
try{
str=tf1.getText();
str=str.substring(1)+str.substring(0,1);
tf1.setText(str);
Thread.sleep(sleeptime);
}catch(InterruptedException e){
System.out.println(e);
break;
}
}
}
public void setButton(){
if(this.isAlive()) b1.setEnabled(false);
if(this.isInterrupted()) b2.setEnabled(false);
}
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
}